Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.

The first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of markers and the number of caps, correspondingly.  Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 ≤ xi, yi ≤ 1000) — the i-th marker's color and diameter, correspondingly. Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 ≤ aj, bj ≤ 1000) — the color and diameter of the j-th cap, correspondingly.

Print two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.

NoteIn the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed — the first and the third markers.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val (coun, color) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){
    case ((count, colors), el) =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
      (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))
  }
  val (coun2, color2) = (1 to m).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){
    case ((count, colors), el) =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
      (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))
  }

  val count = coun.foldLeft(0) {
    case(acc, (size, count)) => acc + Math.min(count, coun2.getOrElse(size, 0))
  }

  val col = color.foldLeft(0) {
    case(acc, (key, count)) => acc + Math.min(count, color2.getOrElse(key, 0))
  }

  println(s"$count $col")

}

object Main {
  import scala.collection.{mutable => mu}

  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val n = nm(0)
    val m = nm(1)

    val a1 = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val a2 = (1 to m).map(_ => readLine().split(" ").map(_.toInt))

    val m1 = mu.Map[Int, mu.Map[Int, Int]]()
    val m2 = mu.Map[Int, mu.Map[Int, Int]]()

    a1.foreach { t =>
      val m = m1.getOrElse(t(1), mu.Map[Int, Int]())
      m1(t(1)) = m
      val prev = m.getOrElse(t(0), 0)
      m(t(0)) = prev + 1
    }

    a2.foreach { t =>
      val m = m2.getOrElse(t(1), mu.Map[Int, Int]())
      m2(t(1)) = m
      val prev = m.getOrElse(t(0), 0)
      m(t(0)) = prev + 1
    }

    var all = 0
    var good = 0
    for( (d, cols) <- m1) {
      val m = m2.getOrElse(d, mu.Map.empty[Int, Int])
      all += cols.values.sum.min(m.values.sum)
      good += cols.map(t => m.getOrElse(t._1, 0).min(t._2)).sum
    }

    print(all + " " + good)
  }
}

import scala.collection.mutable.Map
object Main {
  def readLineOfNums(): Array[Int] = readLine().split(" ").map(_.toInt)
  def prepareMaps(n: Int): (Map[Int, Int], Map[(Int, Int), Int]) = {
    val mapGeneral = Map[Int, Int]()
    val mapPerfect = Map[(Int, Int), Int]()
    for (i <- 1 to n) {
      val Array(y, x) = readLineOfNums()
      if (mapGeneral.contains(x))
        mapGeneral(x) += 1
      else
        mapGeneral += (x -> 1)
      if (mapPerfect.contains((x, y)))
        mapPerfect((x, y)) += 1
      else
        mapPerfect += ((x, y) -> 1)
    }
    (mapGeneral, mapPerfect)
  }
  def main(args: Array[String]) = {
    val Array(n, m) = readLineOfNums()
    val (generalF, perfectF) = prepareMaps(n)
    val (generalK, perfectK) = prepareMaps(m)
    var sumG = 0
    for ((x, y) <- generalF)
      if (generalK.contains(x))
        sumG += List(y, generalK(x)).min
    var sumP = 0
    for(((x,y), z) <- perfectF)
      if (perfectK.contains((x,y)))
        sumP += List(z, perfectK((x, y))).min
    println(sumG.toString + " " + sumP.toString)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val (coun, color) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){
    case ((count, colors), el) =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
      (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))
  }
  val c = (1 to m).foldLeft(0, 0, coun, color) {
    case (acc@(pair, goodPair, d, col), el) =>
      val Array(a, b) = in.next().split(' ').map(_.toInt)
      val dCount = d.getOrElse(b, 0)
      val colCount = col.getOrElse((b, a), 0)

      if (dCount > 0) {
        if (colCount > 0) {
          (pair + 1, goodPair + 1, d + (b -> (dCount - 1)), col + ((b, a) -> (colCount - 1)))
        } else {
          (pair + 1, goodPair + 1, d + (b -> (dCount - 1)), col)
        }
      } else {
        acc
      }
  }

  println(s"${c._1} ${c._2}")

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val (coun, color) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){
    case ((count, colors), el) =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
      (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))
  }
  val c = (1 to m).foldLeft(0, 0, coun, color) {
    case (acc@(pair, goodPair, d, col), el) =>
      val Array(a, b) = in.next().split(' ').map(_.toInt)
      val dCount = d.getOrElse(b, 0)
      val colCount = col.getOrElse((b, a), 0)

      if (dCount > 0) {
        if (colCount > 0) {
          (pair + 1, goodPair + 1, d + (b -> (dCount - 1)), col + ((b, a) -> (colCount - 1)))
        } else {
          (pair + 1, goodPair, d + (b -> (dCount - 1)), col)
        }
      } else {
        acc
      }
  }

  println(s"${c._1} ${c._2}")

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val f = (1 to n).map{_ =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
    (b, a)
  }.sorted.toList
  val c = (1 to m).map{_ =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
    (b, a)
  }.sorted.toList

  def sol(f: List[(Int, Int)], c: List[(Int, Int)], sum: Int = 0, b: Int = 0): (Int, Int) = {
    if (f.isEmpty || c.isEmpty) (sum, b)
    else if (f.head._1 > c.head._1)
      sol(f, c.tail, sum, b)
    else if (f.head._1 < c.head._1)
      sol(f.tail, c, sum, b)
    else if (f.head._2 == c.head._2)
      sol(f.tail, c.tail, sum + 1, b + 1)
    else
      sol(f.tail, c.tail, sum + 1, b)
  }

  val res = sol(f, c)
  println(s"${res._1} ${res._2}")

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val (coun, color) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){
    case ((count, colors), el) =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
      (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))
  }
  val (coun2, color2) = (1 to n).foldLeft(Map.empty[Int, Int], Map.empty[(Int, Int), Int]){
    case ((count, colors), el) =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
      (count + (b -> (count.getOrElse(b, 0) + 1)), colors + ((b, a) -> (colors.getOrElse((b, a), 0) + 1)))
  }

  val count = coun.foldLeft(0) {
    case(acc, (size, count)) => acc + Math.min(count, coun2.getOrElse(size, 0))
  }

  val col = color.foldLeft(0) {
    case(acc, (key, count)) => acc + Math.min(count, color2.getOrElse(key, 0))
  }

  println(s"$count $col")

}


Consider infinite grid of unit cells. Some of those cells are planets. Meta-universe M = {p1, p2, ..., pk} is a set of planets. Suppose there is an infinite row or column with following two properties: 1) it doesn't contain any planet pi of meta-universe M on it; 2) there are planets of M located on both sides from this row or column. In this case we can turn the meta-universe M into two non-empty meta-universes M1 and M2 containing planets that are located on respective sides of this row or column. A meta-universe which can't be split using operation above is called a universe. We perform such operations until all meta-universes turn to universes.Given positions of the planets in the original meta-universe, find the number of universes that are result of described process. It can be proved that each universe is uniquely identified not depending from order of splitting.

The first line of input contains an integer n, (1 ≤ n ≤ 105), denoting the number of planets in the meta-universe. The next n lines each contain integers xi and yi, ( - 109 ≤ xi, yi ≤ 109), denoting the coordinates of the i-th planet. All planets are located in different cells.

Print the number of resulting universes.

NoteThe following figure describes the first test case:

import java.util.TreeSet
import scala.collection.mutable.ArrayBuilder

object F extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  case class Pair(c: Int, i: Int) extends Comparable[Pair] {

    private final val weight = c * 100000L + i

    def compareTo(other: Pair): Int = java.lang.Long.compare(weight, other.weight)

  }

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Pair](n)

  for (i <- 0 until n) {
    val Array(x, y) = readInts(2)
    xs(i) = Pair(x, i)
    ys(i) = Pair(y, i)
  }

  def recurse(keepIdsByX: TreeSet[Pair], keepIdsByY: TreeSet[Pair], separateIds: Array[Int]): Int = {

    val separateByX, separateByY = new TreeSet[Pair]

    for (i <- separateIds) {
      separateByX.add(xs(i))
      keepIdsByX.remove(xs(i))
      separateByY.add(ys(i))
      keepIdsByY.remove(ys(i))
    }

    count(separateByX, separateByY) + count(keepIdsByX, keepIdsByY)
  }

  def count(keepIdsByX: TreeSet[Pair], keepIdsByY: TreeSet[Pair]): Int = {

    val left = keepIdsByX.iterator
    val right = keepIdsByX.descendingIterator
    val top = keepIdsByY.iterator
    val bottom = keepIdsByY.descendingIterator

    var Pair(prevLeftX, leftI) = left.next
    var Pair(prevTopY, topI) = top.next
    var Pair(prevRightX, rightI) = right.next
    var Pair(prevBottomY, bottomI) = bottom.next

    val leftIds, rightIds, topIds, bottomIds = new ArrayBuilder.ofInt
    leftIds += leftI
    rightIds += rightI
    topIds += topI
    bottomIds += bottomI

    var done = false
    var separateIds = Array.empty[Int]

    while (!done && left.hasNext) {

      if (!done) {
        val p = left.next
        if (prevLeftX < p.c - 1) {
          separateIds = leftIds.result
          done = true
        } else {
          leftIds += p.i
          prevLeftX = p.c
        }
      }

      if (!done) {
        val p = right.next
        if (prevRightX > p.c + 1) {
          separateIds = rightIds.result
          done = true
        } else {
          rightIds += p.i
          prevRightX = p.c
        }
      }

      if (!done) {
        val p = top.next
        if (prevTopY < p.c - 1) {
          separateIds = topIds.result
          done = true
        } else {
          topIds += p.i
          prevTopY = p.c
        }
      }

      if (!done) {
        val p = bottom.next
        if (prevBottomY > p.c + 1) {
          separateIds = bottomIds.result
          done = true
        } else {
          bottomIds += p.i
          prevBottomY = p.c
        }
      }

      if (prevLeftX >= prevRightX && prevTopY >= prevBottomY) done = true
    }

    if (separateIds.nonEmpty) recurse(keepIdsByX, keepIdsByY, separateIds)
    else 1
  }

  val allByX, allByY = new TreeSet[Pair]

  for (i <- 0 until n) {
    allByX.add(xs(i))
    allByY.add(ys(i))
  }

  println(count(allByX, allByY))
}

import java.util.TreeSet
import scala.collection.mutable.ArrayBuilder

object F extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  case class Pair(c: Int, id: Int) extends Comparable[Pair] {

    def compareTo(other: Pair): Int =
      if (c < other.c) -1
      else if (c > other.c) 1
      else if (id < other.id) -1
      else if (id > other.id) 1
      else 0

  }

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Pair](n)

  for (i <- 0 until n) {
    val Array(x, y) = readInts(2)
    xs(i) = Pair(x, i)
    ys(i) = Pair(y, i)
  }

  def recurse(keepIdsByX: TreeSet[Pair], keepIdsByY: TreeSet[Pair], separateIds: Array[Int]): Int = {

    val separateByX, separateByY = new TreeSet[Pair]

    for (i <- separateIds) {
      separateByX.add(xs(i))
      keepIdsByX.remove(xs(i))
      separateByY.add(ys(i))
      keepIdsByY.remove(ys(i))
    }

    count(separateByX, separateByY) + count(keepIdsByX, keepIdsByY)
  }

  def count(keepIdsByX: TreeSet[Pair], keepIdsByY: TreeSet[Pair]): Int = {

    val left = keepIdsByX.iterator
    val right = keepIdsByX.descendingIterator
    val top = keepIdsByY.iterator
    val bottom = keepIdsByY.descendingIterator

    var Pair(prevLeftX, leftI) = left.next
    var Pair(prevTopY, topI) = top.next
    var Pair(prevRightX, rightI) = right.next
    var Pair(prevBottomY, bottomI) = bottom.next

    val leftIds, rightIds, topIds, bottomIds = new ArrayBuilder.ofInt
    leftIds += leftI
    rightIds += rightI
    topIds += topI
    bottomIds += bottomI

    var done = false
    var separateIds = Array.empty[Int]

    while (!done && left.hasNext) {

      if (!done) {
        val p = left.next
        if (prevLeftX < p.c - 1) {
          separateIds = leftIds.result
          done = true
        } else {
          leftIds += p.id
          prevLeftX = p.c
        }
      }

      if (!done) {
        val p = right.next
        if (prevRightX > p.c + 1) {
          separateIds = rightIds.result
          done = true
        } else {
          rightIds += p.id
          prevRightX = p.c
        }
      }

      if (!done) {
        val p = top.next
        if (prevTopY < p.c - 1) {
          separateIds = topIds.result
          done = true
        } else {
          topIds += p.id
          prevTopY = p.c
        }
      }

      if (!done) {
        val p = bottom.next
        if (prevBottomY > p.c + 1) {
          separateIds = bottomIds.result
          done = true
        } else {
          bottomIds += p.id
          prevBottomY = p.c
        }
      }

      if (prevLeftX >= prevRightX && prevTopY >= prevBottomY) done = true
    }

    if (separateIds.nonEmpty) recurse(keepIdsByX, keepIdsByY, separateIds)
    else 1
  }

  val allByX, allByY = new TreeSet[Pair]

  for (i <- 0 until n) {
    allByX.add(xs(i))
    allByY.add(ys(i))
  }

  println(count(allByX, allByY))
}


The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.

NoteIn the second sample the name of the corporation consecutively changes as follows:

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val str = in.next()
  var map = ('a' to 'z').map(i => i -> i).toMap
  var backMap = ('a' to 'z').map(i => i -> i).toMap
  val nMap = (1 to m).foreach { _ =>
    val Array(a, b) = in.next().split(' ').map(_.head)
    val fa = backMap(a)
    val fb = backMap(b)
    map += (fa -> b)
    map += (fb -> a)
    backMap += (b -> fa)
    backMap += (a -> fb)
  }
  println(str.map(map).mkString)
}

object B591 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val name = read.toCharArray
    val map = ('a' to 'z').toArray
    for(_ <- 1 to m) {
      val Array(x, y) = readChars(2)
      for(i <- 0 until 26)
        if(map(i) == x)
          map(i) = y
        else if(map(i) == y)
          map(i) = x
    }
    for(i <- name.indices)
      if(map(name(i)-'a') != -1)
        name(i) = map(name(i)-'a')
    println(name.mkString(""))
  }

  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 readChars(n: Int): Array[Char] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.head)
    }

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

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

}

object B591 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val name = read.toCharArray
    val map = ('a' to 'z').toArray
    for(_ <- 1 to m) {
      val Array(x, y) = readChars(2)
      for(i <- 0 until 26)
        if(map(i) == x)
          map(i) = y
        else if(map(i) == y)
          map(i) = x
    }
    println(name.map(a => map(a-'a')).mkString(""))
  }

  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 readChars(n: Int): Array[Char] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.head)
    }

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

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

}

import scala.collection._

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val s = readLine.toCharArray

  val to = Array.tabulate('z' + 1)(i => i.toChar)

  for (_ <- 1 to m) {
    val r = readLine
    val x = r(0)
    val y = r(2)
    for (i <- 'a' to 'z') {
      if (to(i) == x) to(i) = y
      else if (to(i) == y) to(i) = x
    }
  }

  val res = s.map(c => to(c)).mkString

  println(res)
}

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

object B {

  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)

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val name = next.toCharArray
    val letters = new Array[Char](27)
    val positions = new Array[Int](n)
    for (i <- 0 until n) {
      positions(i) = name(i) - 'a'
      letters(positions(i)) = name(i)
    }
    for (i <- 0 until m) {
      val x = next.toCharArray.apply(0)
      val y = next.toCharArray.apply(0)
      var ind = -1
      for (j <- 0 until 27) {
        if (letters(j) == x) {
          letters(j) = y
          ind = j
        }
      }
      for (j <- 0 until 27) {
        if (letters(j) == y && j != ind) {
          letters(j) = x
        }
      }
    }
    for (i <- 0 until positions.length) {
      out.print(letters(positions(i)))
    }
    return 0
  }
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

import CodeForcesApp._

object _591B extends CodeForcesApp {
  override type Result = String

  override def solve(scanner: Scanner) = {
    import scanner._
    val (l, n) = (nextInt(), nextInt())
    val s = nextString()
    var d = Map.empty[Char, Char]
    repeat(n) {
      val (x, y) = (nextChar(), nextChar())
      if (x != y) {
        var (f1, f2) = (false, false)
        d = d map {
          case (i, `x`) =>
            f1 = true
            i -> y
          case (i, `y`) =>
            f2 = true
            i -> x
          case i => i
        }
        if(!f1) d = d + (x -> y)
        if(!f2) d = d + (y -> x)
      }
    }
    s map {i => d.getOrElse(i, i)}
  }

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/********************************[Scala Scanner]*********************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
   * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line
   */
  def nextLine(): String = {
    current = None   // reset
    reader.readLine()
  }
  def lineNumber: Int = reader.getLineNumber
  def nextString(): String = next()
  def nextChar(): Char = next().head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def hasNext = tokenizer().exists(_.hasMoreTokens)
  override def next() = tokenizer().get.nextToken()
  override def close() = reader.close()
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

import CodeForcesApp._

object _591B extends CodeForcesApp {
  override type Result = String

  override def solve(scanner: Scanner) = {
    import scanner._
    val (l, n) = (nextInt(), nextInt())
    val s = nextString()
    var d = Map.empty[Char, Char]
    repeat(n) {
      val (x, y) = (nextChar(), nextChar())
      if (x != y) {
        var (f1, f2) = (false, false)
        d = d map {
          case (i, `x`) =>
            f1 = true
            i -> y
          case (i, `y`) =>
            f2 = true
            i -> x
          case i => i
        }
        if(!f1) d = d + (x -> y)
        if(!f2) d = d + (y -> x)
        //debug(x, y, f1, f2, d)
      }
    }
    s map {i => d.getOrElse(i, i)}
  }

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/********************************[Scala Scanner]*********************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines: Iterator[String] = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  def tokens: Iterator[String] = for {
    line <- lines
    tokenizer = new StringTokenizer(line)
    _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokenizer.nextToken()

  private[this] var current = tokens
  override def hasNext = current.hasNext
  @inline override def next() = current.next()

  /**
   * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line
   */
  def nextLine(): String = {
    current = tokens   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def nextString(): String = next()
  def nextChar(): Char = next().head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close() = reader.close()
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val str = readLine().toCharArray

  val M = scala.collection.mutable.Map[Char, Char]()
  for (ch <- 'a' to 'z') {
    M(ch) = ch
  }

  def change(from: Char, to: Char) = {
    if (from != to) {
      var curr1 = from
      while (M(curr1) != from) curr1 = M(curr1)

      var curr2 = to
      while (M(curr2) != to) curr2 = M(curr2)

      M(curr1) = to
      M(curr2) = from
    }
  }

  for (i <- 1 to m) {
    val Array(x, y) = readLine().split(" ").map(_.charAt(0))
    change(x, y)
  }

  println(str.map { ch => M(ch)}.mkString(""))
}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer
import java.util.HashMap
import java.util.HashSet

object B {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

//    class XXX(val number:Int, var x: Int) {
//      override def toString(): String = {
//        return number + "(" + x + ")"
//      }
//    }

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa2.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val n = line1.nextToken().toInt
    val m = line1.nextToken().toInt

    var name = br.readLine()

//    val actions = new Array[(Char, Char)](m)
//    val
    val map = new HashMap[Char, HashSet[Char]]()
    for (i <- 0 until m) {
      val acL = br.readLine().split(" ")
      val (c1, c2) = (acL(0)(0), acL(1)(0))

      if (c1 != c2) {
        var cur1 = map.get(c1)
        if (cur1 != null) {
          map.remove(c1);
        } else {
          cur1 = new HashSet()
          cur1.add(c1)
        }

        var cur2 = map.get(c2)
        if (cur2 != null) {
          map.remove(c2);
        } else {
          cur2 = new HashSet()
          cur2.add(c2)
        }

        val prev1 = map.get(c2)
        if (prev1 != null) cur1.addAll(prev1)
        map.put(c2, cur1)
//        db(mkMP)
        val prev2 = map.get(c1)
        if (prev2 != null) cur2.addAll(prev2)
        map.put(c1, cur2)
//        db(mkMP)
      }

    }

//    def mkMP(): String = {
//      var res = ""
//      val it = map.entrySet().iterator()
//      while (it.hasNext()) {
//        val entry = it.next()
//        val to = entry.getKey()
//        res += to + "->["
//        val from = entry.getValue()
//        val fromIt = from.iterator()
//        while (fromIt.hasNext()) {
//          res+= fromIt.next() + ", "
//        }
//        res += "]"
//      }
//      res
//    }

    val map2 = new HashMap[Char, Char]()
    val it = map.entrySet().iterator()
    while (it.hasNext()) {
      val entry = it.next()
      val to = entry.getKey()
      val from = entry.getValue()
      val fromIt = from.iterator()
      while (fromIt.hasNext()) {
        map2.put(fromIt.next(), to);
      }
    }

    var res2 = new StringBuffer()
    for(i <- name) {
      if (map2.containsKey(i)) {
        res2.append(map2.get(i))
      } else
        res2.append(i)
    }

    println(res2.toString())

    //---------------------------- parameters reading end --------------------------------

  }

//========================= samples ========================
val sa1 = """6 1
police
p m
"""

val sa2 = """
11 6
abacabadaba
a b
b c
a d
e g
f a
b b
"""

//========================= samples end ====================
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val str = readLine().toCharArray

  val M = scala.collection.mutable.Map[Char, Char]()
  for (ch <- 'a' to 'z') {
    M(ch) = ch
  }

  def change(from: Char, to: Char) = {
    var curr = from
    while (M(curr) != from) curr = M(curr)
    M(curr) = to

    curr = to
    while (M(curr) != to) curr = M(curr)
    M(curr) = from
  }

  for (i <- 1 to m) {
    val Array(x, y) = readLine().split(" ").map(_.charAt(0))
    change(x, y)
  }

  println(str.map { ch => M(ch)}.mkString(""))
}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer
import java.util.HashMap
import java.util.HashSet

object B {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

//    class XXX(val number:Int, var x: Int) {
//      override def toString(): String = {
//        return number + "(" + x + ")"
//      }
//    }

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa2.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val n = line1.nextToken().toInt
    val m = line1.nextToken().toInt

    var name = br.readLine()

//    val actions = new Array[(Char, Char)](m)
//    val
    val map = new HashMap[Char, HashSet[Char]]()
    for (i <- 0 until m) {
      val acL = br.readLine().split(" ")
      val (c1, c2) = (acL(0)(0), acL(1)(0))

      if (c1 != c2) {
        var cur1 = map.get(c1)
        if (cur1 != null) {
          map.remove(c1);
        } else {
          cur1 = new HashSet()
          cur1.add(c1)
        }

        var cur2 = map.get(c2)
        if (cur2 != null) {
          map.remove(c2);
        } else {
          cur2 = new HashSet()
          cur2.add(c2)
        }

        val prev1 = map.get(c2)
        if (prev1 != null) cur1.addAll(prev1)
        map.put(c2, cur1)
        db(mkMP)
        val prev2 = map.get(c1)
        if (prev2 != null) cur2.addAll(prev2)
        map.put(c1, cur2)
        db(mkMP)
      }

    }

    def mkMP(): String = {
      var res = ""
      val it = map.entrySet().iterator()
      while (it.hasNext()) {
        val entry = it.next()
        val to = entry.getKey()
        res += to + "->["
        val from = entry.getValue()
        val fromIt = from.iterator()
        while (fromIt.hasNext()) {
          res+= fromIt.next() + ", "
        }
        res += "]"
      }
      res
    }

    val map2 = new HashMap[Char, Char]()
    val it = map.entrySet().iterator()
    while (it.hasNext()) {
      val entry = it.next()
      val to = entry.getKey()
      val from = entry.getValue()
      val fromIt = from.iterator()
      while (fromIt.hasNext()) {
        map2.put(fromIt.next(), to);
      }
    }

    val map2It = map2.entrySet().iterator()
    while (map2It.hasNext()) {
      val couple = map2It.next()
      name = name.replace(couple.getKey(), couple.getValue())
    }
    println(name)

    //---------------------------- parameters reading end --------------------------------

  }

//========================= samples ========================
val sa2 = """
11 6
abacabadaba
a b
b c
a d
e g
f a
b b
"""

//========================= samples end ====================
}


In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.

The first line of the input contains a single integer t (1 ≤ t ≤ 100) — the number of values of n to be processed. Each of next t lines contains a single integer n (1 ≤ n ≤ 109).

Print the requested sum for each of t integers n given in the input.

NoteThe answer for the first sample is explained in the statement.

import scala.io.StdIn

object Test extends App {
  val ncase = StdIn.readInt()
  for (i <- 0 until ncase) {
    val n = StdIn.readLong()
    val allSum = if (n % 2 == 0) n / 2 * (n + 1) else (n + 1) / 2 * n
    var partialSum: Long = 0
    var pow2: Long = 1
    while (pow2 <= n) {
      partialSum += pow2
      pow2 <<= 1
    }
    println(allSum - partialSum * 2)
  }
}

import scala.io.StdIn

object A {
  def main(args: Array[String]): Unit = {
    val T = StdIn.readInt()
    for (_ <- 1 to T) {
      val n = StdIn.readLong()
      var ans = n * (n + 1) / 2
      var t = 1
      while (t <= n) {
        ans -= 2 * t
        t *= 2
      }
      println(ans)
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt

  def squares(n: Long): Long = {
    var res = 1l
    var sum = 0l
    while (res <= n) {
      sum += res
      res *= 2
    }
    sum
  }

  def sum(n: Long): Long = {
    (n + 1) * n / 2 - 2 * squares(n)
  }

  println((1 to t).map(i => sum(in.next().toInt)).mkString("\n"))
}

object A598 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(t) = readInts(1)
    for(_ <- 1 to t) {
      val Array(n) = readLongs(1)
      val log = (math.log(n)/math.log(2)).toInt

      var ret = (n*(n+1))/2
      for(i <- 0 to log) {
        ret -= math.pow(2, i+1).toLong
      }
      println(ret)
    }
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

import scala.collection.mutable

object A {

  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
    }
  }

  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 t = nextInt
    for (i <- 0 until t) {
      val n = nextInt
      var firstSumPart = 1L * n * (1L + n) / 2
      var num = 1L
      while (num <= n) {
        firstSumPart -= 2L * num
        num *= 2L
      }
      out.println(firstSumPart)
    }
    return 0
  }
}

object A01TrickySum {
  //import java.io.{InputStream, PrintStream}
  //import java.util.Scanner
  import scala.io.StdIn._
  def solve(/*input: InputStream, output: PrintStream*/): Unit = {
    //val sc = new Scanner(input)
    val t = readInt
    (1 to t).foreach( i => {
      val n = readLong()
      val sumaContinua = (n * (n + 1)) / 2L
      //maximo k tal que 2**k <= n
      val k = (0 until 32).filter( i => (1L << i) <= n).last
      val suma2k_1 = (1L << (k + 1)) - 1L
      val ans = sumaContinua - 2L * suma2k_1
      println(ans)

    })
  }
  def main(args: Array[String]): Unit = {
    solve(/*System.in,System.out*/)
  }

}

object A01TrickySum {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  def solve(input: InputStream, output: PrintStream): Unit = {
    val sc = new Scanner(input)
    val t = sc.nextInt
    (1 to t).foreach( i => {
      val n = sc.nextLong()
      val sumaContinua = (n * (n + 1)) / 2L
      //maximo k tal que 2**k <= n
      val k = (0 until 32).filter( i => (1L << i) <= n).last
      val suma2k_1 = (1L << (k + 1)) - 1L
      val ans = sumaContinua - 2L * suma2k_1
      output.println(ans)

    })
  }
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }

}

object Main extends App {
  val ans = (n:Long) => n*(n+1)/2 -Stream.from(0).map(BigInt(0) setBit _ ).dropWhile(_<=n).tail.head+2
  val n = readInt()

  for(a <- 1 to n) {
    val x = readInt()
    println(ans(x))
  }
}

object Main extends App {
  val ans = (n:Long) => n*(n+1)/2 -(0 to 1000).toList.map(BigInt(0) setBit _ ).dropWhile(_<=n).tail.head+2
  val n = readInt()

  for(a <- 1 to n) {
    val x = readInt()
    println(ans(x))
  }
}

object Main extends App {
  val ans = (n:Long) => n*(n+1)/2 -(0 to 1000).map(BigInt(0) setBit _ ).dropWhile(_<=n).tail.head+2
  val n = readInt()

  for(a <- 1 to n) {
    val x = readInt()
    println(ans(x))
  }
}

object Main extends App {
  class PipedObject[T] private[Main] (value:T)
	{
		def |>[R] (f : T => R) = f(this.value)
	}
	implicit def toPiped[T] (value:T) = new PipedObject[T](value)
	def divisible6(a: Long) = if (a % 6 == 0)  true else false
	def isPrime(n: Int) = (2 to n) |> (r => r.foldLeft(r.toSet)((ps, x) => if (ps(x)) ps -- (x * x to n by x) else ps))
	//println( 5L * 7L |> divisible6)
	//println( isPrime(25))
	def calc(n:Int,p:Int): Int = p + (if( 2*p <= n) calc(n, 2*p) else 0)
	var n = readInt()
	for(i <- 1 to n) {
		var r = readInt()
	  println( (r * 1L * (r+1)) / 2 - 2 * calc(r, 1))
	}
}

import scala.io.StdIn

object Test extends App {
  val ncase = StdIn.readInt()
  for (i <- 0 until ncase) {
    val n = StdIn.readLong()
    val allSum = if (n % 2 == 0) n / 2 * (n + 1) else (n + 1) / 2 * n
    var partialSum: Long = 0
    var pow2: Long = 1
    while (pow2 < n) {
      partialSum += pow2
      pow2 <<= 1
    }
    println(allSum - partialSum * 2)
  }
}


It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha.So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly x days. You know the majority of people prefer to go somewhere for a vacation, so Leha immediately went to the travel agency. There he found out that n vouchers left. i-th voucher is characterized by three integers li, ri, costi — day of departure from Vičkopolis, day of arriving back in Vičkopolis and cost of the voucher correspondingly. The duration of the i-th voucher is a value ri - li + 1.At the same time Leha wants to split his own vocation into two parts. Besides he wants to spend as little money as possible. Formally Leha wants to choose exactly two vouchers i and j (i ≠ j) so that they don't intersect, sum of their durations is exactly x and their total cost is as minimal as possible. Two vouchers i and j don't intersect if only at least one of the following conditions is fulfilled: ri < lj or rj < li.Help Leha to choose the necessary vouchers!

The first line contains two integers n and x (2 ≤ n, x ≤ 2·105) — the number of vouchers in the travel agency and the duration of Leha's vacation correspondingly. Each of the next n lines contains three integers li, ri and costi (1 ≤ li ≤ ri ≤ 2·105, 1 ≤ costi ≤ 109) — description of the voucher.

Print a single integer — a minimal amount of money that Leha will spend, or print  - 1 if it's impossible to choose two disjoint vouchers with the total duration exactly x.

NoteIn the first sample Leha should choose first and third vouchers. Hereupon the total duration will be equal to (3 - 1 + 1) + (6 - 5 + 1) = 5 and the total cost will be 4 + 1 = 5.In the second sample the duration of each voucher is 3 therefore it's impossible to choose two vouchers with the total duration equal to 2.

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, x) = readInts(2)
  case class V(l: Int, r: Int, cost: Long) {
    def len = r - l + 1
  }

  val vs = Array.fill(n) {
    val Array(l, r, c) = readInts(3)
    V(l, r, c)
  }

  val vsByLen = vs.groupBy(_.len).map {
    case (k, _vs) => k -> _vs.sortBy(_.l)
  }

  var res = Long.MaxValue

  for (len1 <- vsByLen.keys) {
    val len2 = x - len1
    if (vsByLen.contains(len2)) {
      val vsByLen2 = vsByLen(len2)
      var len2Pos = 0
      var minCostInLen2 = Long.MaxValue
      for (v1 <- vsByLen(len1)) {
        while (len2Pos < vsByLen2.length && vsByLen2(len2Pos).r < v1.l) {
          if (vsByLen2(len2Pos).cost < minCostInLen2) minCostInLen2 = vsByLen2(len2Pos).cost
          len2Pos += 1
        }
        if (minCostInLen2 < Long.MaxValue && v1.cost + minCostInLen2 < res) res = v1.cost + minCostInLen2
      }
    }
  }

  if (res == Long.MaxValue) res = -1
  println(res)
}


This is the easy version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is "11001111", it will be divided into "11", "00" and "1111". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so "11001111" is good. Another example, if $$$s$$$ is "1110011000", it will be divided into "111", "00", "11" and "000", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, "1110011000" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1'($$$1 \leq i \leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good?

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single line with one integer — the minimum number of operations to make $$$s$$$ good.

NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes "1100000000", it can be divided into "11" and "00000000", which lengths are $$$2$$$ and $$$8$$$ respectively. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as "1111110000", "1100001100", "1111001100".In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required.

object Task2 extends App {

  import scala.io.StdIn

  def readLine: String = StdIn.readLine()

  def readNum: Int = StdIn.readLine().toInt

  val testCases = readNum

  for (_ <- 0 until testCases) {
    readLine
    val inputString = readLine.toCharArray
    var pos = 1
    var totalOpsCount = 0

    do {
      if (inputString(pos - 1) != inputString(pos)) {
        totalOpsCount += 1
      }
      pos += 2
    } while (pos <= inputString.length)

    println(totalOpsCount)
  }
}


You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijk we obtain the table:acdefghjk A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.

The first line contains two integers  — n and m (1 ≤ n, m ≤ 100). Next n lines contain m small English letters each — the characters of the table.

Print a single number — the minimum number of columns that you need to remove in order to make the table good.

NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val marked = Array.ofDim[Boolean](m)
  val data = (1 to n).map(_ => in.next())
  val t = (0 until m).foldLeft((0, List((0, n - 1)))) {
    case(acc@(_, Nil), i) =>
//      println("heere")
      acc
    case((x, list), i) =>
//      println(list)
//      println(i)
//      println(x)
      val remove = list.exists {
        case(first, last) => (first until last).exists(j => data(j)(i) > data(j + 1)(i))
      }
      if (remove)
        (x + 1, list)
      else {
        (x, list.flatMap{
          case(first, last) =>
            val res = (first until last).filter(j => data(j)(i) != data(j + 1)(i))
//            println("res")
//            println(res)
//            println((first until last).toList)
//            println("-----------")
            val ans = res.foldLeft((first, List.empty[(Int, Int)])) {
              case((prev, ll), z) => (z + 1, (prev, z) :: ll)
            }
            ((ans._1, last) :: ans._2).filter(i => i._1 != i._2)
        })
      }
  }
  println(t._1)
}

object Main extends App {

  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val table = (0 to n-1) map { _ =>
    readLine.split("").filterNot(_ == "")
  } toList

  def isSorted(seq: List[String]): Boolean = {
    seq.isEmpty ||
      0 == (seq zip seq.tail map { case (a1, a2) => a2 >= a1 } count (_ == false))
  }

  def columnAt(index: Int): List[String] = {
    table map { case r => r(index) }
  }

  val init = (Stream.fill(n)("").toList, 0)
  val (_, rem) = (0 to m-1).foldLeft(init)({
    case ((rows, removed), index) =>
      val cs = columnAt(index)
      val next = (rows zip cs) map { case (row, c) => row + c }
      if(isSorted(next)) (next, removed) else (rows, removed+1)
  })

  println(rem)

}

import scala.collection._

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val ss = Array.fill(n){ readLine }

  var equalToPrev = Array.fill(n){ true }
  equalToPrev(0) = false
  var removedCount = 0

  for (col <- 0 until m) {
    var prev = ss(0)(col)
    val equalToPrev2 = equalToPrev.clone()
    var remove = false
    for (row <- 1 until n) {
      val curr = ss(row)(col)
      if (prev > curr && equalToPrev(row)) {
        remove = true
      } else if (prev < curr) {
        equalToPrev2(row) = false
      }
      prev = curr
    }
    if (remove) removedCount += 1
    else equalToPrev = equalToPrev2
  }

  println(removedCount)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val marked = Array.ofDim[Boolean](m)
  val data = (1 to n).map(_ => in.next())
  val t = (0 until m).foldLeft((0, List((0, n - 1)))) {
    case(acc@(_, Nil), i) =>
//      println("heere")
      acc
    case((x, list), i) =>
//      println(list)
//      println(i)
//      println(x)
      val remove = list.exists {
        case(first, last) => (first until last).exists(j => data(j)(i) > data(j + 1)(i))
      }
      if (remove)
        (x + 1, list)
      else {
        (x, list.flatMap{
          case(first, last) =>
            val res = (first until last).filter(j => data(j)(i) != data(j + 1)(i))
//            println("res")
//            println(res)
//            println((first until last).toList)
//            println("-----------")
            val ans = res.foldLeft((0, List.empty[(Int, Int)])) {
              case((prev, ll), z) => (z + 1, (prev, z) :: ll)
            }
            ((ans._1, last) :: ans._2).filter(i => i._1 != i._2)
        })
      }
  }
  println(t._1)
}

object Main extends App {

  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val table = (0 to n-1) map { _ =>
    readLine.split("").filterNot(_ == "")
  } toList

  def isSorted(seq: List[String]): Boolean = {
    seq.isEmpty ||
      0 == (seq zip seq.tail map { case (a1, a2) => a2 >= a1 } count (_ == false))
  }

  def column(rows: Set[Int], index: Int): List[(String, Int)] = {
    table.zipWithIndex flatMap { case (r, i) => if(rows.contains(i)) List((r(index), i)) else List() }
  }

  def filterEq(column: List[(String, Int)]): Set[Int] = {
    column.groupBy(_._1).flatMap({
      case (v, indices) => if(indices.size > 1) indices.map(_._2) else List()
    }).toSet
  }

  val init = ((0 to n-1).toSet, 0)
  val (_, rem) = (0 to m-1).foldLeft(init)({
    case ((rows, removed), index) =>
      val cs = column(rows, index)
      if(isSorted(cs.map(_._1))) {
        (filterEq(cs), removed)
      } else {
        (rows, removed+1)
      }
  })

  println(rem)

}

object Main extends App {

  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val table = (0 to n-1) map { _ =>
    readLine.split("").filterNot(_ == "")
  } toList

  def isSorted(seq: List[String]): Boolean = {
    0 == (seq zip seq.tail map { case (a1, a2) => a2 >= a1 } count (_ == false))
  }

  def isSortedAt(index: Int): Boolean = {
    isSorted(table map { r => r(index) })
  }

  println((0 to m-1) count (index => !isSortedAt(index)) )

}


Two people are playing a game with a string $$$s$$$, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.Your task is to determine which player will win if both play optimally.

The only line contains the string $$$s$$$, consisting of lowercase latin letters ($$$1 \leq |s| \leq 100\,000$$$), where $$$|s|$$$ means the length of a string $$$s$$$.

If the first player wins, print "Yes". If the second player wins, print "No".

NoteIn the first example the first player is unable to make a turn, so he loses.In the second example first player turns the string into "q", then second player is unable to move, so he loses.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val S = ns()
    val N = S.length
    var cnt = 0

    val stack = mutable.Stack[Char]()
    REP(N) { i =>
      if (stack.nonEmpty && stack.head == S(i)) {
        cnt += 1
        stack.pop()
      } else {
        stack.push(S(i))
      }
    }

    if (cnt % 2 == 0) {
      out.println("No")
    } else {
      out.println("Yes")
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.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 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]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Main {

  def main(args: Array[String]) {
    val std = scala.io.StdIn

    val n = std.readLine()

    var stack = List.empty[Char]

    var count = 0

    for (i <- 0 until n.length) {
      if (stack.isEmpty || stack.head != n(i)) {
        stack = n(i) :: stack
      }
      else {
        stack = stack.tail
        count += 1
      }
    }

    if (count % 2 == 0) {
      println("No")
    }
    else {
      println("Yes")
    }
  }
}

import scala.io.StdIn

object StringGame {

  def step(n: List[Char], a: Char): List[Char] = n match {
    case Nil => List(a)
    case x :: xs => if (x == a) xs else a :: n
  }

  def main(args: Array[String]): Unit = {
    val in = StdIn.readLine().toList
    val res = in.foldLeft[List[Char]](List())(step)
    val isFirstWinner = (in.length - res.length) / 2 % 2 == 1
    println(if (isFirstWinner) "YES" else "NO")
  }

//  def main(args: Array[String]): Unit = {
//    val in = StdIn.readLine()
//    var acc = ""
//    in.foreach { ch =>
//      acc = step(acc, ch)
//    }
//
//    val isFirstWinner = (in.length - acc.length) / 2 % 2 == 1
//    println(if (isFirstWinner) "YES" else "NO")
//  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val S = ns()
    val N = S.length
    var cnt = 0
    val del = Array.ofDim[Boolean](N)
    REP(N) { i =>
      var j = 0
      while (i + j < N && i - 1 - j >= 0 && S(i + j) == S(i - 1 - j) && !del(i - 1 - j)) {
        cnt += 1
        del(i + j) = true
        del(i - 1 - j) = true
        j += 1
      }
    }

    if (cnt % 2 == 0) {
      out.println("No")
    } else {
      out.println("Yes")
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.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 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]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.io.StdIn

object StringGame {

  def play(s: String): String = if (s.isEmpty) s else step(s.head, play(s.tail))

  def step(a: Char, n: String): String = if (n.startsWith(a.toString)) n.drop(1) else a + n

  def main(args: Array[String]): Unit = {
    val in = StdIn.readLine()
    val res = play(in)
    val isFirstWinner = (in.length - res.length) / 2 % 2 == 1
    println(isFirstWinner)
  }
}

import scala.io.StdIn

object StringGame {

  def play(s: String): String = if (s.isEmpty) s else step(s.head, play(s.tail))

  def step(a: Char, n: String): String = if (n.startsWith(a.toString)) n.drop(1) else a + n

  def main(args: Array[String]): Unit = {
    val in = StdIn.readLine()
    val res = play(in)
    val isFirstWinner = (in.length - res.length) / 2 % 2 == 1
    println(res)
  }
}


Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?

The first line contains two integers n, l (1 ≤ n ≤ 1000, 1 ≤ l ≤ 109) — the number of lanterns and the length of the street respectively.  The next line contains n integers ai (0 ≤ ai ≤ l). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.

Print the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.

NoteConsider the second sample. At d = 2 the first lantern will light the segment [0, 4] of the street, and the second lantern will light segment [3, 5]. Thus, the whole street will be lit.

import java.util.StringTokenizer

import scala.Array.canBuildFrom

object _492B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val l = next.toLong
  val a = (1 to n).map(i => next.toLong).sorted.toArray
  val b = (a :+ (-a(0)) :+ (2 * l - a.last)).sorted
  val c = (1 until b.length).map(i => (b(i) - b(i - 1)) / 2.0)
  val ans = c.max
  println("%.14f".format(ans))
}

object B492 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, l) = readLongs(2)
    val input = readLongs(n.toInt).sortBy(identity)
    var res = math.max(2*input.head, 2*(l-input.last))
    for(i <- 1 until input.length) {
      res = math.max(res, input(i)-input(i-1))
    }
    println(res/2.0)
  }
}

import scala.collection._

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, l) = readInts(2)
  val as = readInts(n).distinct.sorted

  var prev = 0
  var max = as(0).toDouble

  for (a <- as) {
    max = math.max(max, (a - prev) / 2.0)
    prev = a
  }
  max = math.max(max, l - as.last)

  println(max)
}

import scala.io.StdIn

object A extends App {

  val Array(m, n) = StdIn.readLine().split(" ").map(_.toLong)

  val arr = StdIn.readLine().split(" ").map(_.toDouble).sortWith(_ < _)

  val result  = if (arr.length == 1) 0 else arr.iterator.sliding(2).withPartial(false).map { x =>
    (x(1) - x.head)/2
  }.max

  var max = Math.max(arr.head, n - arr.last)

  println(Math.max(result, max))

}

object B {
  def main(args: Array[String]) = {
    val nl = readLine().split(' ').map(t => t.toInt)
    val n = nl(0)
    val l = nl(1)
    val lamps = readLine().split(' ').map(t => t.toInt).sorted
    var ans = 2 * math.max(l - lamps(n - 1), lamps(0))
    for (i <- lamps.indices) {
      if (i + 1 < lamps.length) {
        ans = math.max(ans, lamps(i + 1) - lamps(i))
      }
    }
    println(ans / 2.0)
  }
}

import scala.io.StdIn._

object Main2 extends App {
  val Array(_, lastCoordinate) = readLine().split(" ").map(_.toInt)
  val lanternsCoordinates = readLine().split(" ").map(_.toInt).toVector.sorted
  val maxDistanceBetweenLanterns = lanternsCoordinates
    .foldLeft[(Int, Int)]((0, lanternsCoordinates.head)){ case ((maxDistance, previousCoordinate),  currentCoordinate) =>
      (Math.max(maxDistance, currentCoordinate - previousCoordinate), currentCoordinate)
    }._1
  println(Vector(lanternsCoordinates.head, maxDistanceBetweenLanterns/2.0, lastCoordinate - lanternsCoordinates.last).max)
}

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

object Solution {
  def solve(in: FastScanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val l = in.nextInt()
    val a = new Array[Int](n)
    for (i <- 0 until n)
      a(i) = in.nextInt()
    Arrays.sort(a)
    var res: Double = Math.max(a(0), l - a(n - 1))
    for (i <- 1 until n)
      res = Math.max(res, (a(i) - a(i - 1)) / 2.0)
    println(res)
  }

  def main(args: Array[String]): Unit = {
    val in = new FastScanner(System.in)
    val out = new PrintWriter(System.out)
    solve(in, out)
    out.flush()
  }

  class FastScanner(val in: InputStream) {
    var st: StringTokenizer = null
    var br = new BufferedReader(new InputStreamReader(in))

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

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

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

    def close(): Unit = {
      br.close()
    }
  }

}

import scala.math.Ordering._

object Main extends App {
  val Array(n, l) = readLine.split(" ").map(_.toInt)
  val fs: List[Int] = readLine.split(" ").map(_.toInt).toList
  val row: List[Int] = fs.sorted
  val dm: List[Int] = (row zip row.tail).map({
     case (a, b) => b - a
  })
  val d = if(dm.isEmpty) 0 else dm.max
  println("%.9f".format(List(d/2.0, row.head - 0.0, l - row.last).max))
}

import scala.io.StdIn._

object TaskA extends App {
  val (n, l) = readLine.split(" ").map(_.toInt).toList match {
    case x :: y :: Nil => (x, y)
  }

  val lanterns = readLine.split(" ").map(_.toInt).toList.sorted
  val dists = (lanterns.head * 2) :: ((l - lanterns.reverse.head) * 2) :: lanterns.zip(lanterns.tail).map { case (l1, l2) => (l2 - l1) }

  println(dists.sorted.reverse.head / 2.0)
}

object B492 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, l) = readLongs(2)
    val input = readLongs(n.toInt).sortBy(identity)
    var res = math.max(2*input.head, 2*(n-input.last))
    for(i <- 1 until input.length) {
      res = math.max(res, input(i)-input(i-1))
    }
    println(res/2.0)
  }
}

import scala.io.StdIn

object A extends App {

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toLong)

  val arr = StdIn.readLine().split(" ").map(_.toDouble)

  val result = arr.iterator.sliding(2).withPartial(false).map { x =>
    (x(1) - x.head)/2
  }.max

  var max = Math.max(arr.head, n - arr.last)

  println(Math.max(result, max))

}

import scala.io.StdIn

object A extends App {

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toLong)

  val arr = StdIn.readLine().split(" ").map(_.toDouble).sortWith(_ < _)

  val result = arr.iterator.sliding(2).withPartial(false).map { x =>
    (x(1) - x.head)/2
  }.max

  var max = Math.max(arr.head, n - arr.last)

  println(Math.max(result, max))

}

import scala.math.Ordering._

object Main extends App {
  val Array(n, l) = readLine.split(" ").map(_.toInt)
  val fs: List[Int] = readLine.split(" ").map(_.toInt).toList
  val row: List[Int] = fs.sorted :+ l
  val d: Int = (row zip row.tail).map({
     case (a, b) => b - a
  }).max
  println("%.9f".format(d/2.0))
}

import scala.math.Ordering._

object Main extends App {
  val Array(n, l) = readLine.split(" ").map(_.toInt)
  val fs: List[Int] = readLine.split(" ").map(_.toInt).toList
  val row: List[Int] = 0 :: fs.sorted
  val d: Int = (row zip row.tail).map({
     case (a, b) => b - a
  }).max
  println("%.9f".format(List(d/2.0, row.head - 0.0, l - row.last).max))
}


After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal.

First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction.

Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal.

NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val x, f = ni()

    var ans = 0L
    val c = x + f
    rep(N) { i =>
      ans += A(i) / c
      val r = A(i) % c
      if (r > x) ans += 1
    }

    out.println(ans * f)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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 map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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


The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti — the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:   the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n),  the sum of the ti values of the remaining sculptures is maximized. Help the Vice Rector to analyze the criticism — find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.

The first input line contains an integer n (3 ≤ n ≤ 20000) — the initial number of sculptures. The second line contains a sequence of integers t1, t2, ..., tn, ti — the degree of the i-th sculpture's attractiveness ( - 1000 ≤ ti ≤ 1000). The numbers on the line are separated by spaces.

Print the required maximum sum of the sculptures' attractiveness.

NoteIn the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 и 3.

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val divs = (2 to n / 3).filter(i => n % i == 0)
  val data = in.next().split(" ").map(_.toLong)
  var max = data.sum
  divs.foreach { i =>
    var j = 0
    while (j < i) {
      var k = j
      var candidate = 0l
      while (k < n) {
        candidate += data(k)
        k += i
      }
      max = Math.max(candidate, max)
      j += 1
    }
  }
  println(max)
}

object D158 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    var res = in.sum
    val div = divisors(n).filter(n/_ > 2)
    for(d <- div) {
      for(i <- 0 until d) {
        var curr = 0
        for(j <- 0 until n/d) {
          curr += in((i+d*j)%n)
        }
        res = math.max(res, curr)
      }
    }
    println(res)
  }

  def divisors(n: Int): Array[Int] = {
    (1 to n/2).filter(i => n % i == 0).toArray
  }

  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 D158 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    var res = in.sum
    val div = divisors(n).filter(n/_ > 2)
    for(d <- div) {
      for(i <- 0 until d) {
        var curr = 0
        for(j <- 0 until n/d) {
          curr += in((i+d*j)%n)
        }
        res = math.max(res, curr)
      }
    }
    println(res)
  }

  def divisors(n: Int): Array[Int] = {
    val ret = cu.ArrayBuffer.empty[Int]
    var i = 1
    while(i*i <= n) {
      if(n%i == 0)
        ret.append(i, n/i)
      i += 1
    }
    ret.toArray
  }

  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.util.Scanner

object D {
  val in = new Scanner(System.in)

  def main(args: Array[String]) {
    val n = in.nextInt
    val s = Array.fill[Int](n)(in.nextInt())
    var max = Int.MinValue
    for (d <- 1 to n / 3 if n % d == 0) {
      val sum = Array.ofDim[Int](d)
      for (i <- 0 until s.length) {
        sum(i % d) += s(i)
      }
      max = max max sum.max
    }
    println(max)
  }
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P158D extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N = sc.nextInt
  val t = Array.fill(N)(sc.nextInt)

  val divisors = (1 to N / 3).filter(N % _ == 0)

  def svalue(d: Int, r: Int) = {
    @tailrec
    def loop(acc: Int, i: Int): Int =
      if (i >= N) acc
      else loop(acc + t(i), i + d)
    loop(0, r)
  }

  val answer = {
    for {
      d <- divisors
      r <- 0 until d
    } yield svalue(d, r)
  }.max

  out.println(answer)
  out.close
}

object IceSculptures extends App {
  import java.io._
  import java.util.{Scanner => Input}

  val in = new Input(new BufferedReader(new InputStreamReader(System.in)))
  val n = in.nextInt
  val a = new Array[Int](n + 1)
  for (i <- 1 to n) a(i) = in nextInt

  val s = new Array[Int](n + 1)
  var ans = Int.MinValue
  for (l <- 1 to n)
    if (n % l == 0 && n / l >= 3) {
      for (i <- n to (1, -1)) {
        s(i) = a(i) + (if (i + l <= n) s(i + l) else 0)
        if (i <= l && s(i) > ans)
          ans = s(i)
      }
    }
  println(ans)
}

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

object TaskD {
  def main(args: Array[String]) {
    val in = new InputReader(System.in)
    val n = in.nextInt
    val s = Array.fill[Int](n)(in.nextInt)
    var max = Int.MinValue
    for (d <- 1 to n / 3 if n % d == 0) {
      val sum = Array.ofDim[Int](d)
      for (i <- 0 until s.length) {
        sum(i % d) += s(i)
      }
      max = max max sum.max
    }
    println(max)
  }

  class InputReader {
    def this(f: File) {
      this()
      try {
        br = new BufferedReader(new FileReader(f))
      }
    }

    def this(f: InputStream) {
      this()
      br = new BufferedReader(new InputStreamReader(f))
    }

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

    def nextInt: Int = {
      return java.lang.Integer.parseInt(next)
    }

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

    def nextLine: String = {
      try {
        return br.readLine
      }
      return null
    }

    private var br: BufferedReader = null
    private var st: StringTokenizer = null
  }

}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val n = readInt
  val a = readInts zip (0 until n)
  def ans = (3 to n).filter(n % _ == 0).map { x =>
    val groups = a.groupBy(_._2 % (n / x))
    groups.values.map { y: Array[(Int, Int)] =>
      y.map(_._1).sum
    }.max
  }.max

  def main(args: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) {
    val num = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val sums = (3 to num).flatMap{ i =>
      if ( num % i == 0) {
        val counts = num / i
        val sums = new Array[Int](counts)
        for(j <- 0 until a.size) {
          sums(j % counts) += a(j)
        }
        sums
      } else Nil
    }
    println(sums.max)
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val s = readLine
    val t = s.split(" ").map(i => i.toInt)

    println( ((2 until n/2).filter(m => n%m == 0).map(step => {
      (0 until step).map(start =>
        (start until n by step).map(t).sum
      ).max
    }) :+ t.sum).max )
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val divs = (2 to Math.sqrt(n).toInt).filter(i => n % i == 0 && n / i > 3)
  val data = in.next().split(" ").map(_.toInt)
  var max = data.sum
  val indexed = data.zipWithIndex
  divs.foreach { i =>
    var j = 0
    while (j < i) {
      max = Math.max(indexed.foldLeft(0) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)
      j += 1
    }
  }
  println(max)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val divs = (1 to Math.sqrt(n).toInt).filter(n % _ == 0)
  val data = in.next().split(" ").map(_.toInt)
  var max = 0
  val indexed = data.zipWithIndex
  divs.foreach { i =>
    var j = 0
    while (j < i) {
      max = Math.max(indexed.foldLeft(0) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)
      j += 1
    }
  }
  println(max)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val divs = (2 to Math.sqrt(n).toInt + 1).filter(i => n % i == 0 && n / i > 2)
  val data = in.next().split(" ").map(_.toLong)
  var max = data.sum
  val indexed = data.zipWithIndex
  divs.foreach { i =>
    var j = 0
    while (j < i) {
      max = Math.max(indexed.foldLeft(0l) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)
      j += 1
    }
  }
  println(max)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val divs = (2 to Math.sqrt(n).toInt).filter(i => n % i == 0 && n / i > 2)
  val data = in.next().split(" ").map(_.toInt)
  var max = data.sum
  val indexed = data.zipWithIndex
  divs.foreach { i =>
    var j = 0
    while (j < i) {
      max = Math.max(indexed.foldLeft(0) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)
      j += 1
    }
  }
  println(max)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val divs = (2 to Math.sqrt(n).toInt + 1).filter(i => n % i == 0 && n / i > 2)
  if (n == 13860)
    println(divs)
  val data = in.next().split(" ").map(_.toLong)
  var max = data.sum
  val indexed = data.zipWithIndex
  divs.foreach { i =>
    var j = 0
    while (j < i) {
      max = Math.max(indexed.foldLeft(0l) { case(acc, (el, index)) => if (index % i == j) acc + el else acc}, max)
      j += 1
    }
  }
  println(max)
}