Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:   $$$f(0) = a$$$;  $$$f(1) = b$$$;  $$$f(n) = f(n-1) \oplus f(n-2)$$$ when $$$n > 1$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. You are given three integers $$$a$$$, $$$b$$$, and $$$n$$$, calculate $$$f(n)$$$.You have to answer for $$$T$$$ independent test cases.

The input contains one or more independent test cases. The first line of input contains a single integer $$$T$$$ ($$$1 \le T \le 10^3$$$), the number of test cases. Each of the $$$T$$$ following lines contains three space-separated integers $$$a$$$, $$$b$$$, and $$$n$$$ ($$$0 \le a, b, n \le 10^9$$$) respectively.

NoteIn the first example, $$$f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7$$$.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

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

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val a, b, n = ni()
      val ans = n % 3 match {
        case 0 => a
        case 1 => b
        case 2 => a ^ b
      }
      out.println(ans)
    }
  }
}

object A {

  import IO._
  def main(args: Array[String]): Unit = {
    val t = nextInt

    var i = 0
    while (i < t) {
      val a, b, n = nextLong
      val xs = Array(a, b, a ^ b)
      out.println(xs(n.toInt % 3))
      i += 1
    }
    out.flush()
  }

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

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

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

  val Array(t) = readInts(1)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 1 to t) {
    val Array(a, b, n) = readLongs(3)
    val xs = Array(a, b, a ^ b)
    println(xs(n.toInt % 3))
  }

  Console.flush
}

object A {

  def main(args: Array[String]): Unit = {}
  import IO._

  val t = nextInt

  for (_ <- Range(0, t)) {
    val a, b, n = nextLong
    val xs = Array(a, b, a ^ b)
    out.println(xs(n.toInt % 3))
  }
  out.flush()

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

  def main(args: Array[String]): Unit = {}
  import IO._

  val t = nextInt

  for (_ <- 1 to t) {
    val a, b, n = nextLong
    val xs = Array(a, b, a ^ b)
    println(xs(n.toInt % 3))
  }

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

  def main(args: Array[String]): Unit = {}
  import IO._

  val t = nextInt

  var i = 0
  while (i < t) {
    val a, b, n = nextLong
    val xs = Array(a, b, a ^ b)
    out.println(xs(n.toInt % 3))
    i += 1
  }
  out.flush()

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A extends App {

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

  val Array(t) = readInts(1)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 1 to t) {
    val Array(a, b, n) = readLongs(3)
    val xs = Array(a, b, a ^ b)
    println(xs(n.toInt % 3))
  }

  Console.flush
}

object A {

  def main(args: Array[String]): Unit = {}
  import IO._

  val t = nextInt

  for (_ <- 1 to t) {
    val a, b, n = nextLong
    val xs = Array(a, b, a ^ b)
    out.println(xs(n.toInt % 3))
  }
  out.flush()

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

  import IO._
  def main(args: Array[String]): Unit = {
    val t = nextInt

    for (_ <- Range(0, t)) {
      val a, b, n = nextLong
      val xs = Array(a, b, a ^ b)
      out.println(xs(n.toInt % 3))
    }
    out.flush()
  }

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

  import IO._
  def main(args: Array[String]): Unit = {
    val t = nextInt

    for (_ <- 1 to t) {
      val a, b, n = nextLong
      val xs = Array(a, b, a ^ b)
      out.println(xs(n.toInt % 3))
    }
    out.flush()
  }

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}


You are the head of a large enterprise. $$$n$$$ people work at you, and $$$n$$$ is odd (i. e. $$$n$$$ is not divisible by $$$2$$$).You have to distribute salaries to your employees. Initially, you have $$$s$$$ dollars for it, and the $$$i$$$-th employee should get a salary from $$$l_i$$$ to $$$r_i$$$ dollars. You have to distribute salaries in such a way that the median salary is maximum possible.To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:  the median of the sequence $$$[5, 1, 10, 17, 6]$$$ is $$$6$$$,  the median of the sequence $$$[1, 2, 1]$$$ is $$$1$$$. It is guaranteed that you have enough money to pay the minimum salary, i.e $$$l_1 + l_2 + \dots + l_n \le s$$$.Note that you don't have to spend all your $$$s$$$ dollars on salaries.You have to answer $$$t$$$ test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of test cases. The first line of each query contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n < 2 \cdot 10^5$$$, $$$1 \le s \le 2 \cdot 10^{14}$$$) — the number of employees and the amount of money you have. The value $$$n$$$ is not divisible by $$$2$$$. The following $$$n$$$ lines of each query contain the information about employees. The $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$). It is guaranteed that the sum of all $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. $$$\sum\limits_{i=1}^{n} l_i \le s$$$.

For each test case print one integer — the maximum median salary that you can obtain.

NoteIn the first test case, you can distribute salaries as follows: $$$sal_1 = 12, sal_2 = 2, sal_3 = 11$$$ ($$$sal_i$$$ is the salary of the $$$i$$$-th employee). Then the median salary is $$$11$$$.In the second test case, you have to pay $$$1337$$$ dollars to the only employee.In the third test case, you can distribute salaries as follows: $$$sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7$$$. Then the median salary is $$$6$$$.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

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

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._

  /**
    * 単調減少
    * [l, h) 方式
    */
  def findMax(f: Int => Boolean, min: Int, max: Int): Int = {
    var l = min
    var h = max + 1
    while(h - l > 1) {
      val x = (h + l) / 2
      if (f(x)) l = x
      else h = x
    }
    l
  }

  def sort(a: Array[Long]): Array[Long] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    java.util.Arrays.sort(a)
    a
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val MAX = 1e9.toInt
    val inf = 1e15.toLong
    REP(ni()) { _ =>
      val n = ni()
      var s = nl()
      val (l, r) = na2(n)
      s -= sumL(l)

      val v = Array.ofDim[Long](n)
      def f(x: Int): Boolean = {
        REP(n) { i =>
          v(i) = if (r(i) < x) inf
          else if (l(i) >= x) 0
          else {
            x - l(i)
          }
        }

        Workspace.sort(v)
        var cnt = 0L
        REP((n + 1) / 2) { i =>
          if (v(i) == inf) return false
          cnt += v(i)
        }
        s >= cnt
      }

      val ans = findMax(f, 1, MAX)
      out.println(ans)
    }
  }
}


You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi < yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .

The only line contains integer n (1 ≤ n ≤ 5·105).

Print 2n integers — the permuted array a that minimizes the value of the sum s.

/**
  * Created by octavian on 11/02/2016.
  */
object Permutation {

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

    //System.setIn(new FileInputStream("./src/permutation.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/permutation.out")))

    val n = readInt()
    var result: Array[Int] = Array.ofDim[Int](2 * n + 1)

    for (i <- 1 to n / 2) {
      result(i) = 2 * (i - 1) + 1
      result(n - i + 1) = 2 * (i - 1) + 1
    }

    for (i <- 1 to n / 2) {
      result(n + i) = 2 * i
      result(2 * n - i) = 2 * i
    }

    result(2 * n) = n

    if (n % 2 == 0) {
      result(2 * n - (n / 2)) = n
    }
    else {
      result(n - (n / 2)) = n
    }

    println(result.tail.mkString(" "))
  }

}


String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length  are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.

The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.

Output the only number — the sum of the polindrome degrees of all the string's prefixes.

object P7D {
    import io.StdIn._

    val s = readLine

    def main(args : Array[String]) {
        var p = s(0).toLong
        var q = s(0).toLong
        var r = 1L
        val a = Array.ofDim[Int](s.size)
        a(0) = 1
        for (i <- 1 until s.size) {
            p = p * 0x3333333333333333L + s(i)
            r = r * 0x3333333333333333L
            q = q + r * s(i)
            a(i) = if (p == q) a(i - 1 >> 1) + 1 else 0
        }
        println(a.sum)
    }
}


Let's denote a m-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size m × m of this matrix contains at least one zero. Consider the following problem:You are given two integers n and m. You have to construct an m-free square matrix of size n × n such that the number of 1's in this matrix is maximum possible. Print the maximum possible number of 1's in such matrix.You don't have to solve this problem. Instead, you have to construct a few tests for it.You will be given t numbers x1, x2, ..., xt. For every , find two integers ni and mi (ni ≥ mi) such that the answer for the aforementioned problem is exactly xi if we set n = ni and m = mi.

The first line contains one integer t (1 ≤ t ≤ 100) — the number of tests you have to construct. Then t lines follow, i-th line containing one integer xi (0 ≤ xi ≤ 109). Note that in hacks you have to set t = 1.

For each test you have to construct, output two positive numbers ni and mi (1 ≤ mi ≤ ni ≤ 109) such that the maximum number of 1's in a mi-free ni × ni matrix is exactly xi. If there are multiple solutions, you may output any of them; and if this is impossible to construct a test, output a single integer  - 1.

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(t) = readInts(1)

  def calc1(n: Long, m: Long): Long = {
    val d = n / m
    n * n - d * d
  }

  def calcM(n: Long, x: Long): Long = {
    val d = n * n - x
    if (d <= 0) 0 else n / Math.sqrt(d).toInt
  }

  for (_ <- 1 to t) {

    val Array(x) = readInts(1)
    var n = Math.sqrt(x).toInt
    var res = "-1"

    var i = 0
    while (i < 10000 && res == "-1") {
      val m = calcM(n, x)
      if (m > 0 && m <= n && calc1(n, m) == x) res = s"$n $m"
      n += 1
      i += 1
    }

    println(res)
  }
}

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(t) = readInts(1)

  def calc1(n: Long, m: Long): Long = {
    val d = n / m
    n * n - d * d
  }

  def calcM(n: Long, x: Long): Long = {
    val d = n * n - x
    if (d < 0) 0 else Math.sqrt(d).toInt
  }

  for (_ <- 1 to t) {

    val Array(x) = readInts(1)
    var n = Math.sqrt(x).toInt
    var res = "-1"

    for (_ <- 1 to 1000) {
      val m = calcM(n, x)
      if (m > 0 && calc1(n, m) == x) res = s"$n $m"
      n += 1
    }

    println(res)
  }
}

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(t) = readInts(1)

  def calc1(n: Long, m: Long): Long = {
    val d = n / m
    n * n - d * d
  }

  for (_ <- 1 to t) {

    val Array(x) = readInts(1)
    var n = Math.sqrt(x).toInt
    var res = "-1"

    for (_ <- 1 to 10) {
      var m = 1
      while (m <= n && res == "-1") {
        if (calc1(n, m) == x) res = s"$n $m"
        m += 1
      }
      n += 1
    }

    println(res)
  }
}


Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point f of a coordinate line, and Johanna is at point e. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers ti and xi — the number of the gas type and its position.One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly s liters of fuel (regardless of the type of fuel). At the moment of departure from point f Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than s liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right.To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from f to e, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.Write a program that can for the m possible positions of the start fi minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.

The first line of the input contains four positive integers e, s, n, m (1 ≤ e, s ≤ 109, 1 ≤ n, m ≤ 2·105) — the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points.  Next n lines contain two integers each ti, xi (1 ≤ ti ≤ 3,  - 109 ≤ xi ≤ 109), representing the type of the i-th gas station (1 represents Regular-92, 2 — Premium-95 and 3 — Super-98) and the position on a coordinate line of the i-th gas station. Gas stations don't necessarily follow in order from left to right. The last line contains m integers fi ( - 109 ≤ fi < e). Start positions don't necessarily follow in order from left to right. No point of the coordinate line contains more than one gas station. It is possible that some of points fi or point e coincide with a gas station.

Print exactly m lines. The i-th of them should contain two integers — the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point fi. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value. If there is no way to get to Johanna from point fi, the i-th line should look like that "-1 -1" (two numbers minus one without the quotes).

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

object E_Kojo_And_Furarri_a {

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

    class Station(val typpe:Int, val coord:Long) {
      var used = 0l
      var total1 = 0l
      var total2 = 0l
      var total3 = 0l
      var broken = false
      var start = false
      var startInd = 0l
      override def toString(): String = {
        var str = coord + "_" + typeStr(typpe) + used + "[" + total1 + "," + total2 + "]"
        if (start) str = "s" + str
        return str
      }
      def setupTotal(next:Station) = {
        if (next != null) {
          total1 = next.total1
          total2 = next.total2
          total3 = next.total3
        }
        typpe match {
          case 3 => total3 += used
          case 2 => total2 += used
          case 1 => total1 += used
        }
      }
      def incrTotal(value:Long) = {
        typpe match {
          case 3 => total3 += value
          case 2 => total2 += value
          case 1 => total1 += value
        }
      }

      def decrTotal(v1:Long, v2:Long) = {
        total1 -= v1
        total2 -= v2
      }
    }
    def typeStr(typpe:Int) = {
      typpe match {
          case 3 => "A"
          case 2 => "B"
          case 1 => "C"
        }
    }

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = br.readLine().trim().split(" ")
    val e_total = line1(0).toLong
    val s_tank = line1(1).toLong
    val n_stations = line1(2).toInt
    val m_points = line1(3).toInt
    var stations = List[Station]()
    for (i <- 0 until n_stations) {
      val line = br.readLine().trim().split(" ")
      stations ::= new Station(line(0).toInt, line(1).toInt)
    }
    stations = stations.filter(_.coord < e_total)
    db(stations.mkString(" -> "))
    db("AFTER STATIONS LOADED")
    var starts = List[Station]()
    val line2 = br.readLine().split(" ")
    for (i <- 0 until line2.length) {
      val start = new Station(3, line2(i).toLong)
      start.start = true;
      start.startInd = i
      stations ::= start
      starts ::= start
    }
    stations = stations.sortWith { (a,b) => a.coord > b.coord}
    db(stations.mkString(" -> "))
    db("AFTER STARTS LOADED")
    //---------------------------- parameters reading end --------------------------------

    var resSize = 0
    var prevCoord = e_total
    var next:Station = null
    var broken = false
    var processed = List[Station]()
    var toProcess = stations
    val result = new StringBuilder()
    while (resSize < m_points) {
      val st = toProcess.head
      val diff = prevCoord - st.coord
      if (broken || diff > s_tank) {
        broken = true
        st.broken = broken
      } else {
        st.used = diff
        st.setupTotal(next)
        val rest = s_tank - diff
        if (st.typpe > 1 && rest > 0) {
          val redisted = redist(processed, st, rest)
          st.used = st.used + redisted._1
          st.incrTotal(redisted._1)
          st.decrTotal(redisted._2, redisted._3)
        }
      }

      if (st.start) {
        resSize += 1
        db(st.coord + ": " + stations.mkString(" -> "))
      } else {
        next = st
        prevCoord = st.coord
        processed ::= st
      }
      toProcess = toProcess.tail
    }

    starts = starts.sortWith{(a,b) => a.startInd < b.startInd }

    for(st <- starts) {
//      if (debugV) print(st.coord + ": ")
      if (st.broken) {
        result.append("-1 -1\n")
      } else {
        result.append(st.total1 + " " +  st.total2 + "\n")
      }
    }
    println(result.toString())

    def redist(li: List[Station], st:Station, rest:Long):(Long,Long,Long) = {
      if (li == Nil || rest == 0) { return (0,0,0) }
      var result = 0l
      var result1 = 0l
      var result2 = 0l
      val next = li.head
      var toReduce = 0l
      if (next.typpe < st.typpe) {
        toReduce = Math.min(rest, next.used)
        if (!st.start) { //save only for real station
          next.used = next.used- toReduce
        }
        if (next.typpe == 1) {
          result1 = toReduce
        } else if (next.typpe == 2) {
          result2 = toReduce
        }
        val left = rest - toReduce
        result = toReduce
        val other = redist(li.tail, st, left)
        result += other._1
        result1 += other._2
        result2 += other._3
      }
      return (result, result1, result2)
    }

  }

//========================= samples ========================
val sa1 = """
8 4 1 1
2 4
0
"""

val sa2 = """
9 3 2 3
2 3
1 6
-1 0 1
"""

val sa3 = """
20 9 2 4
1 5
2 10
-1 0 1 2
"""

val s7 = """
67 10 9 10
3 -1
1 59
1 39
1 -11
2 29
1 9
1 19
1 49
3 77
27 14 21 36 0 13 57 41 20 28
"""

val s8 = """
216 15 19 10
2 -31
2 100
3 230
1 57
3 42
1 157
2 186
1 113
2 -16
3 245
2 142
1 86
2 -3
3 201
3 128
3 12
3 171
2 27
2 72
98 197 114 0 155 35 36 11 146 27
"""

val s9 = """
386 20 29 30
1 349
2 482
1 112
1 93
2 189
1 207
2 35
2 -5
1 422
1 442
1 402
2 238
3 258
3 54
2 369
2 290
2 329
3 74
3 -62
2 170
1 462
2 15
2 222
1 309
3 150
1 -25
3 130
1 271
1 -43
351 250 91 102 0 286 123 93 100 205 328 269 188 83 73 35 188 223 73 215 199 64 47 379 61 298 295 65 158 211
"""
//========================= samples end ====================
}

import java.io._
import java.lang.Long
import scala.annotation.tailrec

//#322 (Div. 2) E
//581/problem/E
object E_Kojo_And_Furarri {

  class Station(val typpe:Int, val coordinate:Long) {
      var O_value = 0l
      private var _ex_value = 0l
      def ex_value = _ex_value
      def ex_value_= (vv: Long) { _ex_value = vv; calc_value = vv}
      var broken = false
      var total_1 = 0l
      var total_2 = 0l
      var total_3 = 0l
      var calc_value = 0l

      override def toString(): String = {
        var str = ""
        var t = "A"
        typpe match {
          case 3 => t = "A"
          case 2 => t = "B"
          case 1 => t = "C"
        }
        str += coordinate + "_" + t
        if (broken) {
          str += "-1"
        } else {
          str += O_value + "(" + ex_value + ")"
          str += "[" + total_1 + "," + total_2 + "]"
        }
        return str
      }

      def resetCalc() {calc_value = ex_value}
    }

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));
    var debugMode = false

    val line1 = br.readLine().split(" ")
    val e_total = line1(0).toLong
    val s_tank = line1(1).toLong
    val n_stations = line1(2).toInt
    val m_points = line1(3).toInt

    var stations = List[Station]()
    for (i <- 0 until n_stations) {
      val s_line = br.readLine().split(" ")
      val s_coo = s_line(1).toLong
      if (s_coo < e_total) {
        stations = new Station(s_line(0).toInt, s_coo) :: stations
      }
    }
    stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}
    val line2 = br.readLine().split(" ")
    var starts = List[Long]()
    for (i <- 0 until line2.length) {
      starts = line2(i).toLong :: starts
    }
    starts = starts.reverse

    //test inp

//    val inp = """8 4 1 1
//2 4
//0""".split("\n")

//    val inp = """9 3 2 3
//2 3
//1 6
//-1 0 1""".split("\n")

//    val inp = """20 9 2 4
//1 5
//2 10
//-1 0 1 2""".split("\n")

    //system 7
//    val inp = """67 10 9 10
//3 -1
//1 59
//1 39
//1 -11
//2 29
//1 9
//1 19
//1 49
//3 77
//27 14 21 36 0 13 57 41 20 28
//""".split("\n")

      //system 8
//    val inp = """216 15 19 10
//2 -31
//2 100
//3 230
//1 57
//3 42
//1 157
//2 186
//1 113
//2 -16
//3 245
//2 142
//1 86
//2 -3
//3 201
//3 128
//3 12
//3 171
//2 27
//2 72
//98 197 114 0 155 35 36 11 146 27""".split("\n")
////    debugMode = true
//    val line1 = inp(0).trim().split(" ")
//    val e_total = line1(0).toLong
//    val s_tank = line1(1).toLong
//    val n_stations = line1(2).toInt
//    val m_points = line1(3).toInt
//    var stations = List[Station]()
//    for (i <- 1 to n_stations) {
//      val s_line = inp(i).trim.split(" ")
//       val s_coo = s_line(1).toLong
//      if (s_coo < e_total) {
//        stations = new Station(s_line(0).toInt, s_coo) :: stations
//      }
//    }
//    stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}
//    val line2 = inp(n_stations+1).trim.split(" ")
//    var starts = List[Long]()
//    for (i <- 0 until line2.length) {
//      starts = line2(i).toLong :: starts
//    }
//    starts = starts.reverse
//    starts = List(98) //!!!!!

    def redist2(toRedis: List[Station], st: Station, restTotal: Long, marking: Boolean): Long = {
      if (toRedis == Nil) { return 0 }
      var result = 0l
      val next = toRedis.head
      if (restTotal == 0) return 0
      var toReduce = 0l
      if (next.typpe < st.typpe) {
        if (marking) {
          toReduce = Math.min(restTotal, next.ex_value)
          next.ex_value = next.ex_value - toReduce
        } else {
          toReduce = Math.min(restTotal, next.calc_value)
          next.calc_value = next.calc_value - toReduce
        }
        result = toReduce + redist2(toRedis.tail, next, restTotal - toReduce, marking)
      }
      return result
    }

    def mark(toMark: List[Station], end: Long): List[Station] = {
      var result = List[Station]()
      var prevCoord = end
      var broken = false
      for (st <- toMark) {
        val diff = prevCoord - st.coordinate
        prevCoord = st.coordinate
        if (broken || diff > s_tank) {
          broken = true
          st.broken = broken
          st.ex_value = -1
        } else {
          st.O_value = diff
          st.ex_value = st.O_value
          val rest = s_tank - diff
          if (st.typpe > 1 && rest > 0) {
            val redisted = redist2(result, st, rest, true)
            st.O_value = st.O_value + redisted
            st.ex_value = st.O_value
          }
        }
        result = st :: result
        printMarks(result)
      }
      result
    }

    def printMarks(marks: List[Station]) {
      if (!debugMode) return
      var str = ""
      for(st <- marks) {
        str += st.toString() + " -> "
      }
      println(str)
    }

    def debug(str: String) {
      if (debugMode)
        println(str)
    }

    //mark
    val marked = mark(stations, e_total)
    debug("------- MARKED -------")

    //update total
    updateTotal(stations,0,0,0,true)

    printMarks(marked)
    debug("------- TOTALLED -------")

    //calc starts
    for (point <- starts) {
      marked.foreach { _.resetCalc() }
      calcPoint(point)
    }

    def calcPoint(point: Long) {
      val tankEnd = point + s_tank
      if (tankEnd >= e_total) {
        printRes(0,0)
        return
      }
      var li = findStList(point, marked)
      if (li == Nil || li.head.broken || tankEnd < li.head.coordinate) {
        printRes(-1,-1)
        return
      }
      val diff = li.head.coordinate - point

      val startSt = new Station(3, point)
      redist2(li, startSt, s_tank - diff, false)
      li = startSt :: li
      updateTotal(li.reverse,0,0,0,false)

      printRes(startSt.total_1, startSt.total_2)

    }

    def printRes(t92:Long, t95:Long) {
      println(t92 +" " + t95)
    }

    @tailrec
    def findStList(start: Long, li: List[Station]): List[Station] = {
      if (li == Nil || start < li.head.coordinate) li
      else findStList(start, li.tail)
    }

    @tailrec
    def updateTotal(toTotal: List[Station], total_1: Long, total_2: Long, total_3: Long, marking:Boolean):Unit = {
      if (toTotal == Nil) return
      val st = toTotal.head
      if (st.broken) {
        st.total_1 = -1
        st.total_2 = -1
        st.total_3 = -1
      } else {
        st.total_1 = total_1
        st.total_2 = total_2
        st.total_3 = total_3
        var value = st.ex_value
        if (!marking) {
          value = st.calc_value
        }
        st.typpe match {
          case 1 => st.total_1 += value
          case 2 => st.total_2 += value
          case 3 => st.total_3 += value
        }
      }
      updateTotal(toTotal.tail, st.total_1, st.total_2, st.total_3, marking)
    }

  }
}

import java.io._
import java.lang.Long
import scala.annotation.tailrec

//#322 (Div. 2) E
//581/problem/E
object E_Kojo_And_Furarri {

  def main(args: Array[String]): Unit = {
    var marking = true

    class Station(val typpe:Int, val coordinate:Long) {
      var O_value = 0l
      private var _ex_value = 0l
      def ex_value = _ex_value
      def ex_value_= (vv: Long) { _ex_value = vv; calc_value = vv}
      private var _broken = false
      def broken = _broken
      def broken_=(vv:Boolean) {_broken = vv; calc_broken = vv}
      var calc_broken = false
      var total_1 = 0l
      var total_2 = 0l
      var total_3 = 0l
      var calc_value = 0l

      override def toString(): String = {
        var str = ""
        var t = "A"
        typpe match {
          case 3 => t = "A"
          case 2 => t = "B"
          case 1 => t = "C"
        }
        str += coordinate + "_" + t
        if (broken) {
          str += "-1"
        } else {
          if (marking) {
            str += O_value + "(" + ex_value + ")"
          } else {
            str += O_value + "(" + calc_value + ")"
          }
          str += "[" + total_1 + "," + total_2 + "]"
        }
        return str
      }

      def resetCalc() {calc_value = ex_value; calc_broken = calc_broken}
    }

    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));
    var debugMode = false

    val line1 = br.readLine().split(" ")
    val e_total = line1(0).toLong
    val s_tank = line1(1).toLong
    val n_stations = line1(2).toInt
    val m_points = line1(3).toInt

    var stations = List[Station]()
    for (i <- 0 until n_stations) {
      val s_line = br.readLine().split(" ")
      val s_coo = s_line(1).toLong
      if (s_coo < e_total) {
        stations = new Station(s_line(0).toInt, s_coo) :: stations
      }
    }
    stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}
    val line2 = br.readLine().split(" ")
    var starts = List[Long]()
    for (i <- 0 until line2.length) {
      starts = line2(i).toLong :: starts
    }
    starts = starts.reverse

    //test inp

//    val inp = """8 4 1 1
//2 4
//0""".split("\n")

//    val inp = """9 3 2 3
//2 3
//1 6
//-1 0 1""".split("\n")

//    val inp = """20 9 2 4
//1 5
//2 10
//-1 0 1 2""".split("\n")

    //system 7
//    val inp = """67 10 9 10
//3 -1
//1 59
//1 39
//1 -11
//2 29
//1 9
//1 19
//1 49
//3 77
//27 14 21 36 0 13 57 41 20 28
//""".split("\n")

      //system 8
//    val inp = """216 15 19 10
//2 -31
//2 100
//3 230
//1 57
//3 42
//1 157
//2 186
//1 113
//2 -16
//3 245
//2 142
//1 86
//2 -3
//3 201
//3 128
//3 12
//3 171
//2 27
//2 72
//98 197 114 0 155 35 36 11 146 27""".split("\n")

//val inp = """386 20 29 30
//1 349
//2 482
//1 112
//1 93
//2 189
//1 207
//2 35
//2 -5
//1 422
//1 442
//1 402
//2 238
//3 258
//3 54
//2 369
//2 290
//2 329
//3 74
//3 -62
//2 170
//1 462
//2 15
//2 222
//1 309
//3 150
//1 -25
//3 130
//1 271
//1 -43
//351 250 91 102 0 286 123 93 100 205 328 269 188 83 73 35 188 223 73 215 199 64 47 379 61 298 295 65 158 211
//""".split("\n")
//
////    debugMode = true
//    val line1 = inp(0).trim().split(" ")
//    val e_total = line1(0).toLong
//    val s_tank = line1(1).toLong
//    val n_stations = line1(2).toInt
//    val m_points = line1(3).toInt
//    var stations = List[Station]()
//    for (i <- 1 to n_stations) {
//      val s_line = inp(i).trim.split(" ")
//       val s_coo = s_line(1).toLong
//      if (s_coo < e_total) {
//        stations = new Station(s_line(0).toInt, s_coo) :: stations
//      }
//    }
//    stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}
//    val line2 = inp(n_stations+1).trim.split(" ")
//    var starts = List[Long]()
//    for (i <- 0 until line2.length) {
//      starts = line2(i).toLong :: starts
//    }
//    starts = starts.reverse
//    starts = List(286)
//    starts = List(188)
//    starts = List(269)
//    starts = List(64)

    def redist2(toRedis: List[Station], st: Station, restTotal: Long, marking: Boolean): Long = {
      if (toRedis == Nil) { return 0 }
      var result = 0l
      val next = toRedis.head
      if (restTotal == 0) return 0
      var toReduce = 0l
      if (next.typpe < st.typpe) {
        if (marking) {
          toReduce = Math.min(restTotal, next.ex_value)
          next.ex_value = next.ex_value - toReduce
        } else {
          toReduce = Math.min(restTotal, next.calc_value)
          next.calc_value = next.calc_value - toReduce
        }
        result = toReduce + redist2(toRedis.tail, st, restTotal - toReduce, marking)
      }
      return result
    }

    def mark(toMark: List[Station], end: Long, marking:Boolean, distLimit: Long): List[Station] = {
      var result = List[Station]()
      var prevCoord = end
      var broken = false
      for (st <- toMark) {
//        if (st.coordinate == 93) {
//          println("it's it")
//        }
        val diff = prevCoord - st.coordinate
        prevCoord = st.coordinate
        if (broken || diff > s_tank) {
          broken = true
          st.broken = broken
          st.ex_value = -1
          st.calc_value = -1
        } else {
          if (marking) {
            st.O_value = diff
            st.ex_value = st.O_value
            val rest = s_tank - diff
            if (st.typpe > 1 && rest > 0) {
              val redisted = redist2(result, st, rest, marking)
//              st.O_value = st.O_value + redisted
              st.ex_value = st.O_value + redisted
            }
          } else {
            st.calc_broken = false
            st.calc_value = st.O_value
            val rest = s_tank - diff
            if (rest > 0) {
//              if (result == Nil) {
//               val redisted = Math.min(rest, distLimit)
//               st.calc_value = st.O_value + redisted
//              } else {
                val redisted = redist2(result, st, rest, marking)
                st.calc_value = st.O_value + redisted
//              }
            }
          }
        }
        result = st :: result
        printMarks(result)
      }
      result
    }

    def printMarks(marks: List[Station]) {
      if (!debugMode) return
      var str = ""
      for(st <- marks) {
        str += st.toString() + " -> "
      }
      println(str)
    }

    def debug(str: String) {
      if (debugMode)
        println(str)
    }

    //mark
    val marked = mark(stations, e_total, true, 0)
    debug("------- MARKED -------")

    //update total
    updateTotal(stations,0,0,0,true)

    printMarks(marked)
    debug("------- TOTALLED -------")

    //calc starts
    marking = false
    for (point <- starts) {
      marked.foreach { _.resetCalc() }
      calcPoint(point)
    }

    def calcPoint(point: Long) {
      val tankEnd = point + s_tank
      if (tankEnd >= e_total) {
        printRes(0,0)
        return
      }
      var li = findStList(point, marked)

      var toReset = getForReset(li, point + s_tank*3)
      var toResetInv = toReset._1.reverse
      debug("----- BEFORE RESET -----")
      printMarks(toResetInv)
      mark(toResetInv, toReset._2, false, toReset._3)
      debug("----- AFTER RESET -----")
      printMarks(toResetInv)

      if (li == Nil || li.head.broken || tankEnd < li.head.coordinate) {
        printRes(-1,-1)
        return
      }
      val diff = li.head.coordinate - point

      val startSt = new Station(3, point)

      redist2(li, startSt, s_tank - diff, false)
      li = startSt :: li
      updateTotal(li.reverse,0,0,0,false)
      printMarks(li)

//      if (debugMode)
//        print("point=" + point + "  ")
      printRes(startSt.total_1, startSt.total_2)

    }

    def getForReset(all:List[Station], max:Long): (List[Station], Long, Long) ={
      if (all == Nil) return (Nil, e_total, 0)
      if (all.head.coordinate < max) {
        val nextRes = getForReset(all.tail, max)
        var limit = nextRes._3
        if (all.tail != Nil) {
          limit = Math.min(limit, all.tail.head.coordinate - all.head.coordinate)
        }
        (all.head :: nextRes._1, nextRes._2, limit)
      } else {
        (Nil, all.head.coordinate, s_tank - all.head.ex_value)
      }
    }

    def printRes(t92:Long, t95:Long) {
      println(t92 +" " + t95)
    }

    @tailrec
    def findStList(start: Long, li: List[Station]): List[Station] = {
      if (li == Nil || start < li.head.coordinate) li
      else findStList(start, li.tail)
    }

    @tailrec
    def updateTotal(toTotal: List[Station], total_1: Long, total_2: Long, total_3: Long, marking:Boolean):Unit = {
      if (toTotal == Nil) return
      val st = toTotal.head
      if (st.broken) {
        st.total_1 = -1
        st.total_2 = -1
        st.total_3 = -1
      } else {
        st.total_1 = total_1
        st.total_2 = total_2
        st.total_3 = total_3
        var value = st.ex_value
        if (!marking) {
          value = st.calc_value
        }
        st.typpe match {
          case 1 => st.total_1 += value
          case 2 => st.total_2 += value
          case 3 => st.total_3 += value
        }
      }
      updateTotal(toTotal.tail, st.total_1, st.total_2, st.total_3, marking)
    }

  }
}

import java.io._
import java.lang.Long
import scala.annotation.tailrec

//#322 (Div. 2) E
//581/problem/E
object E_Kojo_And_Furarri {

  class Station(val typpe:Int, val coordinate:Long) {
//      var O_type = typpe;
      var O_value = 0l
//      var ex_type = 0;
      var ex_value = 0l
      var broken = false
      var total_1 = 0l
      var total_2 = 0l
      var total_3 = 0l

      override def toString(): String = {
        var str = ""
        var t = "A"
        typpe match {
          case 3 => t = "A"
          case 2 => t = "B"
          case 1 => t = "C"
        }
        str += coordinate + "_" + t
        if (broken) {
          str += "-1"
        } else {
          str += O_value + "(" + ex_value + ")"
          str += "[" + total_1 + "," + total_2 + "]"
        }
        return str
      }
    }

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));
    var debugMode = false

        val line1 = br.readLine().split(" ")
        val e_total = line1(0).toLong
        val s_tank = line1(1).toLong
        val n_stations = line1(2).toInt
        val m_points = line1(3).toInt

        var stations = List[Station]()
        for (i <- 0 until n_stations) {
          val s_line = br.readLine().split(" ")
          stations = new Station(s_line(0).toInt, s_line(1).toLong) :: stations
        }
        val line2 = br.readLine().split(" ")
        var starts = List[Long]()
        for (i <- 0 until line2.length) {
          starts = line2(i).toLong :: starts
        }
        starts = starts.reverse

    //test inp
    //    val e_total = 8l
    //    val s_tank = 4l
    //    val n_stations = 1
    //    val m_points = 1
    //    var stations = List[Station](new Station(2, 4)).reverse
    //    var starts = List[Long](0)
    //
    //    debugMode = true
    //    val e_total = 9l
    //    val s_tank = 3l
    //    val n_stations = 2
    //    val m_points = 3
    //    var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse
    //    var starts = List[Long](-1, 0, 1)

    //    val e_total = 20l
    //    val s_tank = 9l
    //    val n_stations = 2
    //    val m_points = 4
    //    var stations = List[Station](new Station(1, 5), new Station(2, 10)).reverse
    //    var starts = List[Long](-1, 0, 1, 2)
    //
    //    val e_total = 10l
    //    val s_tank = 3l
    //    val n_stations = 4
    //    val m_points = 1
    //    var stations = List[Station](new Station(1, 2), new Station(2, 4), new Station(3, 6),
    //        new Station(2, 8)).reverse
    //    var starts = List[Long](1,0)

//    val e_total = 9l
//    val s_tank = 3l
//    val n_stations = 2
//    val m_points = 3
//    var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse
//    var starts = List[Long](-1, 0, 1)

    var total_1 = 0l
    var total_2 = 0l
    var total_3 = 0l

    def redist(toRedis: List[Station], st: Station, restTotal: Long): Long = {
      var rest = restTotal
      for (next <- toRedis) {
        if (rest == 0 || next.typpe > st.typpe) return restTotal - rest
        val toReduce = Math.min(rest, next.ex_value)
        next.ex_value = next.ex_value - toReduce
        rest = rest - toReduce
      }
      return restTotal - rest
    }

    def mark(toMark: List[Station], end: Long): List[Station] = {
      var result = List[Station]()
      var prevCoord = end
      var broken = false
      for (st <- toMark) {
        val diff = prevCoord - st.coordinate
        prevCoord = st.coordinate
        if (broken || diff > s_tank) {
          broken = true
          st.broken = broken
          st.ex_value = -1
        } else {
          st.O_value = diff
          st.ex_value = diff
          val rest = s_tank - diff
          if (st.typpe > 1 && rest > 0) {
            val redisted = redist(result, st, rest)
            st.O_value = st.O_value + redisted
          }
        }
        result = st :: result
        printMarks(result)
      }
      result
    }

    def printMarks(marks: List[Station]) {
      if (!debugMode) return
      var str = ""
      for(st <- marks) {
        str += st.toString() + " -> "
      }
      println(str)
    }

    def debug(str: String) {
      if (debugMode)
        println(str)
    }

    //mark
    val marked = mark(stations, e_total)
    debug("------- MARKED -------")

    //update total
    for (st <- stations) {
      updateTotal(st)
    }
    printMarks(marked)
    debug("------- TOTALLED -------")

    //calc starts
    for (point <- starts) {
      calcPoint(point)
    }

    def calcPoint(point: Long) {
      val finalStart = point + s_tank
      if (finalStart >= e_total) {
        printRes(0,0)
        return
      }
      val li = findStList(point, marked)
      if (li == Nil || li.head.broken || finalStart < li.head.coordinate) {
        printRes(-1,-1)
        return
      }
      val spli = split(li, point + s_tank)
      val left = new Station(3, point) :: spli._1
      var right1 = 0l
      var right2 = 0l
      if (spli._2 != null) {
        right1 = spli._2.total_1
        right2 = spli._2.total_2
      }
      if (spli._1 == Nil) {
        printRes(right1, right2)
        return
      }
      val subMax: Long = if (spli._2 == null){ e_total } else {spli._2.coordinate}

      val leftRev = left.reverse
      val subMarked = mark(leftRev, subMax)
      total_1 = 0
      total_2 = 0
      total_3 = 0
      for (st <- leftRev) {
        updateTotal(st)
      }
//      println("SUB MARKET TOTALLED")
//      printMarks(subMarked)
      var left1 = 0l
      var left2 = 0l
      if (subMarked != Nil) {
        left1 = subMarked.head.total_1
        left2 = subMarked.head.total_2
      }
      printRes(left1+right1, left2+right2)
    }

    def printRes(t92:Long, t95:Long) {
      println(t92 +" " + t95)
    }

    def split(li: List[Station], max: Long): (List[Station], Station) = {
      var result = List[Station]()
      for(st <- li) {
        if (st.coordinate >= max) {
          return (result, st)
        } else {
          result = new Station(st.typpe, st.coordinate) :: result
        }
      }
      return (result.reverse, null)
    }

    @tailrec
    def findStList(start: Long, li: List[Station]): List[Station] = {
      if (li == Nil || start < li.head.coordinate) li
      else findStList(start, li.tail)
    }

    def updateTotal(st:Station) = {
      if (st.broken) {
        total_1 = -1
        total_2 = -1
        total_3 = -1
      } else {
        st.typpe match {
          case 1 => total_1 += st.ex_value
          case 2 => total_2 += st.ex_value
          case 3 => total_3 += st.ex_value
        }
      }
      st.total_1 = total_1
      st.total_2 = total_2
      st.total_3 = total_3
    }

  }
}

import java.io._
import java.lang.Long
import scala.annotation.tailrec

//#322 (Div. 2) E
//581/problem/E
object E_Kojo_And_Furarri {

  class Station(val typpe:Int, val coordinate:Long) {
      var O_value = 0l
      var ex_value = 0l
      var broken = false
      var total_1 = 0l
      var total_2 = 0l
      var total_3 = 0l

      override def toString(): String = {
        var str = ""
        var t = "A"
        typpe match {
          case 3 => t = "A"
          case 2 => t = "B"
          case 1 => t = "C"
        }
        str += coordinate + "_" + t
        if (broken) {
          str += "-1"
        } else {
          str += O_value + "(" + ex_value + ")"
          str += "[" + total_1 + "," + total_2 + "]"
        }
        return str
      }
    }

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));
    var debugMode = false

    val line1 = br.readLine().split(" ")
    val e_total = line1(0).toLong
    val s_tank = line1(1).toLong
    val n_stations = line1(2).toInt
    val m_points = line1(3).toInt

    var stations = List[Station]()
    for (i <- 0 until n_stations) {
      val s_line = br.readLine().split(" ")
      val s_coo = s_line(1).toLong
      if (s_coo < e_total) {
        stations = new Station(s_line(0).toInt, s_coo) :: stations
      }
    }
    stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}
    val line2 = br.readLine().split(" ")
    var starts = List[Long]()
    for (i <- 0 until line2.length) {
      starts = line2(i).toLong :: starts
    }
    starts = starts.reverse

    //test inp
    //    val e_total = 8l
    //    val s_tank = 4l
    //    val n_stations = 1
    //    val m_points = 1
    //    var stations = List[Station](new Station(2, 4)).reverse
    //    var starts = List[Long](0)
    //
    //    debugMode = true
    //    val e_total = 9l
    //    val s_tank = 3l
    //    val n_stations = 2
    //    val m_points = 3
    //    var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse
    //    var starts = List[Long](-1, 0, 1)

    //    val e_total = 20l
    //    val s_tank = 9l
    //    val n_stations = 2
    //    val m_points = 4
    //    var stations = List[Station](new Station(1, 5), new Station(2, 10)).reverse
    //    var starts = List[Long](-1, 0, 1, 2)
    //
    //    val e_total = 10l
    //    val s_tank = 3l
    //    val n_stations = 4
    //    val m_points = 1
    //    var stations = List[Station](new Station(1, 2), new Station(2, 4), new Station(3, 6),
    //        new Station(2, 8)).reverse
    //    var starts = List[Long](1,0)

    //    val e_total = 9l
    //    val s_tank = 3l
    //    val n_stations = 2
    //    val m_points = 3
    //    var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse
    //    var starts = List[Long](-1, 0, 1)

//    debugMode = true
//    val e_total = 18l
//    val s_tank = 9l
//    val n_stations = 2
//    val m_points = 1
//    var stations = List[Station](new Station(2, 9), new Station(1, 12)).reverse
//    var starts = List[Long](0)

//    debugMode = true
//    val e_total = 67l
//    val s_tank = 10l
//    val n_stations = 9
//    val m_points = 10
//    var stations = List[Station](new Station(3, -1), new Station(1, 59),
//        new Station(1, 39), new Station(1, -11), new Station(2, 29), new Station(1, 9)
//        , new Station(1, 19), new Station(1, 49), new Station(3, 77))
//    stations = stations.filter(_.coordinate < e_total).sortWith { (a,b) => a.coordinate > b.coordinate}
//    var starts = List[Long](27, 14, 21, 36, 0, 13, 57, 41, 20, 28)

    var total_1 = 0l
    var total_2 = 0l
    var total_3 = 0l

    def redist(toRedis: List[Station], st: Station, restTotal: Long): Long = {
      var rest = restTotal
      for (next <- toRedis) {
        if (rest == 0 || next.typpe > st.typpe) return restTotal - rest
        val toReduce = Math.min(rest, next.ex_value)
        next.ex_value = next.ex_value - toReduce
        rest = rest - toReduce
      }
      return restTotal - rest
    }

    def mark(toMark: List[Station], end: Long): List[Station] = {
      var result = List[Station]()
      var prevCoord = end
      var broken = false
      for (st <- toMark) {
        val diff = prevCoord - st.coordinate
        prevCoord = st.coordinate
        if (broken || diff > s_tank) {
          broken = true
          st.broken = broken
          st.ex_value = -1
        } else {
          st.O_value = diff
          st.ex_value = st.O_value
          val rest = s_tank - diff
          if (st.typpe > 1 && rest > 0) {
            val redisted = redist(result, st, rest)
            st.O_value = st.O_value + redisted
            st.ex_value = st.O_value
          }
        }
        result = st :: result
        printMarks(result)
      }
      result
    }

    def printMarks(marks: List[Station]) {
      if (!debugMode) return
      var str = ""
      for(st <- marks) {
        str += st.toString() + " -> "
      }
      println(str)
    }

    def debug(str: String) {
      if (debugMode)
        println(str)
    }

    //mark
    val marked = mark(stations, e_total)
    debug("------- MARKED -------")

    //update total
    for (st <- stations) {
      updateTotal(st)
    }
    printMarks(marked)
    debug("------- TOTALLED -------")

    //calc starts
    for (point <- starts) {
      calcPoint(point)
    }

    def calcPoint(point: Long) {
      val finalStart = point + s_tank
      if (finalStart >= e_total) {
        printRes(0,0)
        return
      }
      val li = findStList(point, marked)
      if (li == Nil || li.head.broken || finalStart < li.head.coordinate) {
        printRes(-1,-1)
        return
      }
      val spli = split(li, point + s_tank)
      val left = new Station(3, point) :: spli._1
      var right1 = 0l
      var right2 = 0l
      if (spli._2 != null) {
        right1 = spli._2.total_1
        right2 = spli._2.total_2
      }
      if (spli._1 == Nil) {
        printRes(right1, right2)
        return
      }
      val subMax: Long = if (spli._2 == null){ e_total } else {spli._2.coordinate}

      val leftRev = left.reverse
      val subMarked = mark(leftRev, subMax)
      total_1 = 0
      total_2 = 0
      total_3 = 0
      for (st <- leftRev) {
        updateTotal(st)
      }
//      println("SUB MARKET TOTALLED")
//      printMarks(subMarked)
      var left1 = 0l
      var left2 = 0l
      if (subMarked != Nil) {
        left1 = subMarked.head.total_1
        left2 = subMarked.head.total_2
      }
      printRes(left1+right1, left2+right2)
    }

    def printRes(t92:Long, t95:Long) {
      println(t92 +" " + t95)
    }

    def split(li: List[Station], max: Long): (List[Station], Station) = {
      var result = List[Station]()
      for(st <- li) {
        if (st.coordinate >= max) {
          return (result, st)
        } else {
          result = new Station(st.typpe, st.coordinate) :: result
        }
      }
      return (result.reverse, null)
    }

    @tailrec
    def findStList(start: Long, li: List[Station]): List[Station] = {
      if (li == Nil || start < li.head.coordinate) li
      else findStList(start, li.tail)
    }

    def updateTotal(st:Station) = {
      if (st.broken) {
        total_1 = -1
        total_2 = -1
        total_3 = -1
      } else {
        st.typpe match {
          case 1 => total_1 += st.ex_value
          case 2 => total_2 += st.ex_value
          case 3 => total_3 += st.ex_value
        }
      }
      st.total_1 = total_1
      st.total_2 = total_2
      st.total_3 = total_3
    }

  }
}

import java.io._
import java.lang.Long
import scala.annotation.tailrec

//581 E
object E_Kojo_And_Furarri {

  class Station(val typpe:Int, val coordinate:Long) {
//      var O_type = typpe;
      var O_value = 0l
//      var ex_type = 0;
      var ex_value = 0l
      var broken = false
      var total_1 = 0l
      var total_2 = 0l
      var total_3 = 0l

      override def toString(): String = {
        var str = ""
        var t = "A"
        typpe match {
          case 3 => t = "A"
          case 2 => t = "B"
          case 1 => t = "C"
        }
        str += coordinate + "_" + t
        if (broken) {
          str += "-1"
        } else {
          str += O_value + "(" + ex_value + ")"
          str += "[" + total_1 + "," + total_2 + "]"
        }
        return str
      }
    }

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));
    var debugMode = false

    val line1 = br.readLine().split(" ")
    val e_total = line1(0).toLong
    val s_tank = line1(1).toLong
    val n_stations = line1(2).toInt
    val m_points = line1(3).toInt

    var stations = List[Station]()
    for (i <- 0 until n_stations) {
      val s_line = br.readLine().split(" ")
      stations = new Station(s_line(0).toInt, s_line(1).toLong) :: stations
    }
    val line2 = br.readLine().split(" ")
    var starts = List[Long]()
    for (i <- 0 until line2.length) {
      starts = line2(i).toLong :: starts
    }

    //test inp
//    val e_total = 8l
//    val s_tank = 4l
//    val n_stations = 1
//    val m_points = 1
//    var stations = List[Station](new Station(2, 4)).reverse
//    var starts = List[Long](0)
//
//    debugMode = true
//    val e_total = 9l
//    val s_tank = 3l
//    val n_stations = 2
//    val m_points = 3
//    var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse
//    var starts = List[Long](-1, 0, 1)

//    val e_total = 20l
//    val s_tank = 9l
//    val n_stations = 2
//    val m_points = 4
//    var stations = List[Station](new Station(1, 5), new Station(2, 10)).reverse
//    var starts = List[Long](-1, 0, 1, 2)
//
//    val e_total = 10l
//    val s_tank = 3l
//    val n_stations = 4
//    val m_points = 1
//    var stations = List[Station](new Station(1, 2), new Station(2, 4), new Station(3, 6),
//        new Station(2, 8)).reverse
//    var starts = List[Long](1,0)

    var total_1 = 0l
    var total_2 = 0l
    var total_3 = 0l

    def redist(toRedis: List[Station], st: Station, restTotal: Long): Long = {
      var rest = restTotal
      for (next <- toRedis) {
        if (rest == 0 || next.typpe > st.typpe) return restTotal - rest
        val toReduce = Math.min(rest, next.ex_value)
        next.ex_value = next.ex_value - toReduce
        rest = rest - toReduce
      }
      return restTotal - rest
    }

    def mark(toMark: List[Station], end: Long): List[Station] = {
      var result = List[Station]()
      var prevCoord = end
      var broken = false
      for (st <- toMark) {
        val diff = prevCoord - st.coordinate
        prevCoord = st.coordinate
        if (broken || diff > s_tank) {
          broken = true
          st.broken = broken
          st.ex_value = -1
        } else {
          st.O_value = diff
          st.ex_value = diff
          val rest = s_tank - diff
          if (st.typpe > 1 && rest > 0) {
            val redisted = redist(result, st, rest)
            st.O_value = st.O_value + redisted
          }
        }
        result = st :: result
        printMarks(result)
      }
      result
    }

    def printMarks(marks: List[Station]) {
      if (!debugMode) return
      var str = ""
      for(st <- marks) {
        str += st.toString() + " -> "
      }
      println(str)
    }

    def debug(str: String) {
      if (debugMode)
        println(str)
    }

    //mark
    val marked = mark(stations, e_total)
    debug("------- MARKED -------")

    //update total
    for (st <- stations) {
      updateTotal(st)
    }
    printMarks(marked)
    debug("------- TOTALLED -------")

    //calc starts
    for (point <- starts) {
      calcPoint(point)
    }

    def calcPoint(point: Long) {
      val finalStart = point + s_tank
      if (finalStart >= e_total) {
        printRes(0,0)
        return
      }
      val li = findStList(point, marked)
      if (li == Nil || li.head.broken || finalStart < li.head.coordinate) {
        printRes(-1,-1)
        return
      }
      val spli = split(li, point + s_tank)
      val left = new Station(3, point) :: spli._1
      var right1 = 0l
      var right2 = 0l
      if (spli._2 != null) {
        right1 = spli._2.total_1
        right2 = spli._2.total_2
      }
      if (spli._1 == Nil) {
        printRes(right1, right2)
        return
      }
      val subMax: Long = if (spli._2 == null){ e_total } else {spli._2.coordinate}

      val leftRev = left.reverse
      val subMarked = mark(leftRev, subMax)
      total_1 = 0
      total_2 = 0
      total_3 = 0
      for (st <- leftRev) {
        updateTotal(st)
      }
//      println("SUB MARKET TOTALLED")
//      printMarks(subMarked)
      var left1 = 0l
      var left2 = 0l
      if (subMarked != Nil) {
        left1 = subMarked.head.total_1
        left2 = subMarked.head.total_2
      }
      printRes(left1+right1, left2+right2)
    }

    def printRes(t92:Long, t95:Long) {
      println(t92 +" " + t95)
    }

    def split(li: List[Station], max: Long): (List[Station], Station) = {
      var result = List[Station]()
      for(st <- li) {
        if (st.coordinate >= max) {
          return (result, st)
        } else {
          result = new Station(st.typpe, st.coordinate) :: result
        }
      }
      return (result.reverse, null)
    }

    @tailrec
    def findStList(start: Long, li: List[Station]): List[Station] = {
      if (li == Nil || start < li.head.coordinate) li
      else findStList(start, li.tail)
    }

    def updateTotal(st:Station) = {
      if (st.broken) {
        total_1 = -1
        total_2 = -1
        total_3 = -1
      } else {
        st.typpe match {
          case 1 => total_1 += st.ex_value
          case 2 => total_2 += st.ex_value
          case 3 => total_3 += st.ex_value
        }
      }
      st.total_1 = total_1
      st.total_2 = total_2
      st.total_3 = total_3
    }

  }
}

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

object E_Kojo_And_Furarri_a {

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

    class Station(val typpe:Int, val coord:Long) {
      var used = 0l
      var total1 = 0l
      var total2 = 0l
      var total3 = 0l
      var broken = false
      var start = false
      var startInd = 0l
      override def toString(): String = {
        var str = coord + "_" + typeStr(typpe) + used + "[" + total1 + "," + total2 + "]"
        if (start) str = "s" + str
        return str
      }
      def setupTotal(next:Station) = {
        if (next != null) {
          total1 = next.total1
          total2 = next.total2
          total3 = next.total3
        }
        typpe match {
          case 3 => total3 += used
          case 2 => total2 += used
          case 1 => total1 += used
        }
      }
      def incrTotal(value:Long) = {
        typpe match {
          case 3 => total3 += value
          case 2 => total2 += value
          case 1 => total1 += value
        }
      }

      def decrTotal(v1:Long, v2:Long) = {
        total1 -= v1
        total2 -= v2
      }
    }
    def typeStr(typpe:Int) = {
      typpe match {
          case 3 => "A"
          case 2 => "B"
          case 1 => "C"
        }
    }

//    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = br.readLine().trim().split(" ")
    val e_total = line1(0).toLong
    val s_tank = line1(1).toLong
    val n_stations = line1(2).toInt
    val m_points = line1(3).toInt
    var stations = List[Station]()
    for (i <- 0 until n_stations) {
      val line = br.readLine().trim().split(" ")
      stations ::= new Station(line(0).toInt, line(1).toInt)
    }
    stations = stations.filter(_.coord < e_total)
    db(stations.mkString(" -> "))
    db("AFTER STATIONS LOADED")
    var starts = List[Station]()
    val line2 = br.readLine().split(" ")
    for (i <- 0 until line2.length) {
      val start = new Station(3, line2(i).toLong)
      start.start = true;
      start.startInd = i
      stations ::= start
      starts ::= start
    }
    stations = stations.sortWith { (a,b) => a.coord > b.coord}
    db(stations.mkString(" -> "))
    db("AFTER STARTS LOADED")
    //---------------------------- parameters reading end --------------------------------

    var resSize = 0
    var prevCoord = e_total
    var next:Station = null
    var broken = false
    var processed = List[Station]()
    var toProcess = stations
    while (resSize < m_points) {
      val st = toProcess.head
      if (st.coord == 100) {
        db("here")
      }
      val diff = prevCoord - st.coord
      if (broken || diff > s_tank) {
        broken = true
        st.broken = broken
      } else {
        st.used = diff
        st.setupTotal(next)
        val rest = s_tank - diff
        if (st.typpe > 1 && rest > 0) {
          val redisted = redist(processed, st, rest)
          st.used = st.used + redisted._1
          st.incrTotal(redisted._1)
          st.decrTotal(redisted._2, redisted._3)
        }
      }

      if (st.start) {
        resSize += 1
        db(st.coord + ": " + stations.mkString(" -> "))
      } else {
        next = st
        prevCoord = st.coord
        processed ::= st
      }
      toProcess = toProcess.tail
    }

    starts = starts.sortWith{(a,b) => a.startInd < b.startInd }

    for(st <- starts) {
      if (debugV) print(st.coord + ": ")
      if (st.broken) {
        println("-1 -1")
      } else {
        println(st.total1 + " " +  st.total2)
      }
    }

    def redist(li: List[Station], st:Station, rest:Long):(Long,Long,Long) = {
      if (li == Nil || rest == 0) { return (0,0,0) }
      var result = 0l
      var result1 = 0l
      var result2 = 0l
      val next = li.head
      var toReduce = 0l
      if (next.typpe < st.typpe) {
        toReduce = Math.min(rest, next.used)
        if (!st.start) { //save only for real station
          next.used = next.used- toReduce
        }
        if (next.typpe == 1) {
          result1 = toReduce
        } else if (next.typpe == 2) {
          result2 = toReduce
        }
        val left = rest - toReduce
        result = toReduce
        val other = redist(li.tail, st, left)
        result += other._1
        result1 += other._2
        result2 += other._3
      }
      return (result, result1, result2)
    }

  }

//========================= samples ========================
val sa1 = """
8 4 1 1
2 4
0
"""

val sa2 = """
9 3 2 3
2 3
1 6
-1 0 1
"""

val sa3 = """
20 9 2 4
1 5
2 10
-1 0 1 2
"""

val s7 = """
67 10 9 10
3 -1
1 59
1 39
1 -11
2 29
1 9
1 19
1 49
3 77
27 14 21 36 0 13 57 41 20 28
"""

val s8 = """
216 15 19 10
2 -31
2 100
3 230
1 57
3 42
1 157
2 186
1 113
2 -16
3 245
2 142
1 86
2 -3
3 201
3 128
3 12
3 171
2 27
2 72
98 197 114 0 155 35 36 11 146 27
"""

val s9 = """
386 20 29 30
1 349
2 482
1 112
1 93
2 189
1 207
2 35
2 -5
1 422
1 442
1 402
2 238
3 258
3 54
2 369
2 290
2 329
3 74
3 -62
2 170
1 462
2 15
2 222
1 309
3 150
1 -25
3 130
1 271
1 -43
351 250 91 102 0 286 123 93 100 205 328 269 188 83 73 35 188 223 73 215 199 64 47 379 61 298 295 65 158 211
"""
//========================= samples end ====================
}

import java.io._
import java.lang.Long
import scala.annotation.tailrec

//#322 (Div. 2) E
//581/problem/E
object E_Kojo_And_Furarri {

  class Station(val typpe:Int, val coordinate:Long) {
      var O_value = 0l
      var ex_value = 0l
      var broken = false
      var total_1 = 0l
      var total_2 = 0l
      var total_3 = 0l

      override def toString(): String = {
        var str = ""
        var t = "A"
        typpe match {
          case 3 => t = "A"
          case 2 => t = "B"
          case 1 => t = "C"
        }
        str += coordinate + "_" + t
        if (broken) {
          str += "-1"
        } else {
          str += O_value + "(" + ex_value + ")"
          str += "[" + total_1 + "," + total_2 + "]"
        }
        return str
      }
    }

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));
    var debugMode = false

    val line1 = br.readLine().split(" ")
    val e_total = line1(0).toLong
    val s_tank = line1(1).toLong
    val n_stations = line1(2).toInt
    val m_points = line1(3).toInt

    var stations = List[Station]()
    for (i <- 0 until n_stations) {
      val s_line = br.readLine().split(" ")
      stations = new Station(s_line(0).toInt, s_line(1).toLong) :: stations
    }
    val line2 = br.readLine().split(" ")
    var starts = List[Long]()
    for (i <- 0 until line2.length) {
      starts = line2(i).toLong :: starts
    }
    starts = starts.reverse

    //test inp
    //    val e_total = 8l
    //    val s_tank = 4l
    //    val n_stations = 1
    //    val m_points = 1
    //    var stations = List[Station](new Station(2, 4)).reverse
    //    var starts = List[Long](0)
    //
    //    debugMode = true
    //    val e_total = 9l
    //    val s_tank = 3l
    //    val n_stations = 2
    //    val m_points = 3
    //    var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse
    //    var starts = List[Long](-1, 0, 1)

    //    val e_total = 20l
    //    val s_tank = 9l
    //    val n_stations = 2
    //    val m_points = 4
    //    var stations = List[Station](new Station(1, 5), new Station(2, 10)).reverse
    //    var starts = List[Long](-1, 0, 1, 2)
    //
    //    val e_total = 10l
    //    val s_tank = 3l
    //    val n_stations = 4
    //    val m_points = 1
    //    var stations = List[Station](new Station(1, 2), new Station(2, 4), new Station(3, 6),
    //        new Station(2, 8)).reverse
    //    var starts = List[Long](1,0)

    //    val e_total = 9l
    //    val s_tank = 3l
    //    val n_stations = 2
    //    val m_points = 3
    //    var stations = List[Station](new Station(2, 3), new Station(1, 6)).reverse
    //    var starts = List[Long](-1, 0, 1)

//    debugMode = true
//    val e_total = 18l
//    val s_tank = 9l
//    val n_stations = 2
//    val m_points = 1
//    var stations = List[Station](new Station(2, 9), new Station(1, 12)).reverse
//    var starts = List[Long](0)

    var total_1 = 0l
    var total_2 = 0l
    var total_3 = 0l

    def redist(toRedis: List[Station], st: Station, restTotal: Long): Long = {
      var rest = restTotal
      for (next <- toRedis) {
        if (rest == 0 || next.typpe > st.typpe) return restTotal - rest
        val toReduce = Math.min(rest, next.ex_value)
        next.ex_value = next.ex_value - toReduce
        rest = rest - toReduce
      }
      return restTotal - rest
    }

    def mark(toMark: List[Station], end: Long): List[Station] = {
      var result = List[Station]()
      var prevCoord = end
      var broken = false
      for (st <- toMark) {
        val diff = prevCoord - st.coordinate
        prevCoord = st.coordinate
        if (broken || diff > s_tank) {
          broken = true
          st.broken = broken
          st.ex_value = -1
        } else {
          st.O_value = diff
          st.ex_value = st.O_value
          val rest = s_tank - diff
          if (st.typpe > 1 && rest > 0) {
            val redisted = redist(result, st, rest)
            st.O_value = st.O_value + redisted
            st.ex_value = st.O_value
          }
        }
        result = st :: result
        printMarks(result)
      }
      result
    }

    def printMarks(marks: List[Station]) {
      if (!debugMode) return
      var str = ""
      for(st <- marks) {
        str += st.toString() + " -> "
      }
      println(str)
    }

    def debug(str: String) {
      if (debugMode)
        println(str)
    }

    //mark
    val marked = mark(stations, e_total)
    debug("------- MARKED -------")

    //update total
    for (st <- stations) {
      updateTotal(st)
    }
    printMarks(marked)
    debug("------- TOTALLED -------")

    //calc starts
    for (point <- starts) {
      calcPoint(point)
    }

    def calcPoint(point: Long) {
      val finalStart = point + s_tank
      if (finalStart >= e_total) {
        printRes(0,0)
        return
      }
      val li = findStList(point, marked)
      if (li == Nil || li.head.broken || finalStart < li.head.coordinate) {
        printRes(-1,-1)
        return
      }
      val spli = split(li, point + s_tank)
      val left = new Station(3, point) :: spli._1
      var right1 = 0l
      var right2 = 0l
      if (spli._2 != null) {
        right1 = spli._2.total_1
        right2 = spli._2.total_2
      }
      if (spli._1 == Nil) {
        printRes(right1, right2)
        return
      }
      val subMax: Long = if (spli._2 == null){ e_total } else {spli._2.coordinate}

      val leftRev = left.reverse
      val subMarked = mark(leftRev, subMax)
      total_1 = 0
      total_2 = 0
      total_3 = 0
      for (st <- leftRev) {
        updateTotal(st)
      }
//      println("SUB MARKET TOTALLED")
//      printMarks(subMarked)
      var left1 = 0l
      var left2 = 0l
      if (subMarked != Nil) {
        left1 = subMarked.head.total_1
        left2 = subMarked.head.total_2
      }
      printRes(left1+right1, left2+right2)
    }

    def printRes(t92:Long, t95:Long) {
      println(t92 +" " + t95)
    }

    def split(li: List[Station], max: Long): (List[Station], Station) = {
      var result = List[Station]()
      for(st <- li) {
        if (st.coordinate >= max) {
          return (result, st)
        } else {
          result = new Station(st.typpe, st.coordinate) :: result
        }
      }
      return (result.reverse, null)
    }

    @tailrec
    def findStList(start: Long, li: List[Station]): List[Station] = {
      if (li == Nil || start < li.head.coordinate) li
      else findStList(start, li.tail)
    }

    def updateTotal(st:Station) = {
      if (st.broken) {
        total_1 = -1
        total_2 = -1
        total_3 = -1
      } else {
        st.typpe match {
          case 1 => total_1 += st.ex_value
          case 2 => total_2 += st.ex_value
          case 3 => total_3 += st.ex_value
        }
      }
      st.total_1 = total_1
      st.total_2 = total_2
      st.total_3 = total_3
    }

  }
}


Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configuration?

The first line contains integer n (1 ≤ n ≤ 50000). The second line contains n non-negative numbers that do not exceed 109, the i-th written number is the number of matches in the i-th matchbox. It is guaranteed that the total number of matches is divisible by n.

Print the total minimum number of moves.

import scala.annotation.tailrec

object Devu {
  def main(args: Array[String]) {
	  val n = readLine().toInt
	  val d = readLine().split(" ").map(_.toLong)
	  val goal = d.reduceLeft(_ + _) / n
	  @tailrec
	  def cnt(x: Int, g: Long, acc: Long): Long = {
	    if (x >= n) acc
	    else (g - d(x)) match {
	      case 0 => cnt(x + 1, goal, acc)
	      case z if z > 0 => cnt(x + 1, goal + z, acc + z)
	      case z if z < 0 => cnt(x + 1, goal + z, acc - z)
	    }
	  }
	  println(cnt(0, goal, 0))
  }
}

//package template

object Template {
	def main(args: Array[String]) {
		var n = readLine.toInt
		var input = readLine.split(' ').map(_.toLong)
		if(n == 1){
			print(0)
		}
		else{
			var avarage = 0L
			for(i <- input){
				avarage += i
			}
			avarage /= n
			var answer = 0L
			var current = avarage
			var next = input(0)
			var dif = 0L
			for(i <- 0 until n){
				dif = avarage - current
				current = next - dif
				if(i != n-1)next = input(i+1)
				answer += Math.abs(dif)
			}
			print(answer)
		}
	}
}

//package template

object Template {
	def main(args: Array[String]) {
		var n = readLine.toInt
		var input = readLine.split(' ').map(_.toInt)
		if(n == 1){
			print(0)
		}
		else{
			var avarage = 0
			for(i <- input){
				avarage += i
			}
			avarage /= n
			var answer = 0
			var current = avarage
			var next = input(0)
			var dif = 0
			for(i <- 0 until n){
				dif = avarage - current
				current = next - dif
				if(i != n-1)next = input(i+1)
				answer += Math.abs(dif)
			}
			print(answer)
		}
	}
}


Your company was appointed to lay new asphalt on the highway of length $$$n$$$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $$$g$$$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $$$b$$$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $$$g$$$ good days, $$$b$$$ bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days $$$1, 2, \dots, g$$$ are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $$$n = 5$$$ then at least $$$3$$$ units of the highway should have high quality; if $$$n = 4$$$ then at least $$$2$$$ units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains three integers $$$n$$$, $$$g$$$ and $$$b$$$ ($$$1 \le n, g, b \le 10^9$$$) — the length of the highway and the number of good and bad days respectively.

Print $$$T$$$ integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.

NoteIn the first test case, you can just lay new asphalt each day, since days $$$1, 3, 5$$$ are good.In the second test case, you can also lay new asphalt each day, since days $$$1$$$-$$$8$$$ are good.

import java.io.PrintWriter
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString(): String = reader.readLine()

    def multiTest(f: () => Unit): Unit = {
        var t = readInt()
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        var Array(n,g,b) = readArrayInt().map(_.toLong)
        val ng = n / 2 + n % 2

        val minTotal = n / (g + b)*(g + b) + n % (g + b)
        val minG = ng / g * g + ng % g + (ng / g - (if (ng % g == 0) 1 else 0))* b

        println(math.max(minTotal, minG))
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
    }
}

import java.io.PrintWriter
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString(): String = reader.readLine()

    def multiTest(f: () => Unit): Unit = {
        var t = readInt()
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        var Array(n,g,b) = readArrayInt().map(_.toLong)
        val ng = n / 2 + n % 2

        val minTotal = n / (g + b)*(g + b) + n % (g + b)
        val minG = ng / g * g + ng % g + (ng / g - 1)* b

        println(math.max(minTotal, minG))
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
    }
}


Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .

The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105). The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree. It's guaranteed that the given graph is a tree.

Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.

NoteTree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)Bipartite graph definition: https://en.wikipedia.org/wiki/Bipartite_graphIn the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).

import scala.annotation.tailrec
import scala.collection.mutable

/**
  * @see http://codeforces.com/contest/862/problem/B
  *      TIME LIMIT EXCEEDED :(
  */

object TAILREC_BMahmoudAndEhabAndTheBipartiteness extends App {
  /**
    * Bicoloring based of dfs
    */
  def bicoloring(g: mutable.HashMap[Int, List[Int]]): (Long, Long) = {
    @tailrec
    def dfs(h: List[(Int, Int, List[Int], Int)], cts: (Long, Long)): (Long, Long) = {
      if (h.isEmpty) cts
      else {
        val (p, u, adj, c) = h.head
        if (adj.isEmpty) dfs(h.tail, (cts._1 + (c ^ 1), cts._2 + (c ^ 0)))
        else {
          val v = adj.head
          if (v == p) dfs((p, u, adj.tail, c) :: h.tail, cts)
          else dfs((u, v, g(v), if (c == 0) 1 else 0) :: (p, u, adj.tail, c) :: h.tail, cts)
        }
      }
    }

    dfs(List((0, 1, g(1), 0)), (0L, 0L))
  }

  /**
    * 1 <= n <= math.pow(10, 5)
    */
  val n = scala.io.StdIn.readLine().toInt

  /**
    * The adjacency-list representation of a graph
    * g is a connected acyclic graph
    */
  val g = (0 until n - 1).foldLeft(new mutable.HashMap[Int, List[Int]]) { (g, _) =>
    val Array(u, v) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    g(v) = u :: g.getOrElse(v, Nil)
    g(u) = v :: g.getOrElse(u, Nil)
    g
//    g + (v -> (u :: g.getOrElse(v, Nil)), u -> (v :: g.getOrElse(u, Nil)))
  }

  val (a, b) = bicoloring(g)
  println(a * b - n + 1)
}

import scala.collection.mutable.ArrayBuffer

/**
  * @see http://codeforces.com/contest/862/problem/B
  */

object BMahmoudAndEhabAndTheBipartiteness extends App {
  /**
    * Bicoloring based of dfs
    */
  def bicoloring(g: ArrayBuffer[List[Int]]): (Long, Long) = {
    var cts = (0L, 0L)

    def dfs(u: Int, v: Int, c: Int): Unit = {
      cts = (cts._1 + (c ^ 1), cts._2 + (c ^ 0))
      g(v).foreach(p => if (p != u) dfs(v, p, if (c == 0) 1 else 0))
    }

    dfs(0, 1, 0)
    cts
  }

  /**
    * 1 <= n <= math.pow(10, 5)
    */
  val n = scala.io.StdIn.readLine().toInt

  /**
    * The adjacency-list representation of a graph
    * g is a connected acyclic graph
    */
  val g = (0 until n - 1).foldLeft(ArrayBuffer.fill[List[Int]](100005)(Nil)) { (g: ArrayBuffer[List[Int]], _) =>
    val Array(u, v) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    g(u) = v :: g(u)
    g(v) = u :: g(v)
    g
  }

  val (a, b) = bicoloring(g)
  println(a * b - n + 1)
}

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

object Main{
  def main(args: Array[String]) {
    val bf = new BufferedReader(new InputStreamReader(System.in))
    val N = bf.readLine.toInt
    val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(" ")
    val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)
    val G = E groupBy(_._1) mapValues (_ map(_._2))
    def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList.toMap;
    val black = coloring.filter{case (id, color) => color == 0}.size
    val white = N - black

    println(black.toLong * white - (N - 1));
  }
}

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

object Main{
  def main(args: Array[String]) {
    val bf = new BufferedReader(new InputStreamReader(System.in))
    val N = bf.readLine.toInt
    val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(" ")
    val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)
    val G = E groupBy(_._1) mapValues (_ map(_._2))
    def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList;
    val black = coloring.filter{case (id, color) => color == 0}.size
    val white = N - black

    println(black.toLong * white - (N - 1));
  }
}

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

object Main{
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val N = sc.nextInt
    val edgesLines = for (i <- 0 until (N - 1)) yield (sc.nextInt, sc.nextInt)
    val E = edgesLines.flatMap(e => List(e, e.swap))
    val G = E.groupBy{case (from, to) => from}.mapValues(_.map{case (from, to) => to})
    def Color(id: Int, p: Int, color: Int): Iterator[Tuple2[Int, Int]] = Iterator((id, color)) ++ G(id).filter(_ != p).map(Color(_, id, 1 - color)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList
    val black = coloring.count{case (id, color) => color == 0}
    val white = N - black

    println(black.toLong * white - (N - 1));
  }
}

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

object Main{
  def main(args: Array[String]) {
    val bf = new BufferedReader(new InputStreamReader(System.in))
    val N = bf.readLine.toInt
    val edgesLines = for (i <- 0 until (N - 1)) yield bf.readLine.split(" ")
    val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(e => List(e, e.swap))
    val G = E.groupBy{case (from, to) => from}.mapValues(_.map{case (from, to) => to})
    def Color(id: Int, p: Int, color: Int): Iterator[Tuple2[Int, Int]] = Iterator((id, color)) ++ G(id).filter(_ != p).map(Color(_, id, 1 - color)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList
    val black = coloring.count{case (id, color) => color == 0}
    val white = N - black

    println(black.toLong * white - (N - 1));
  }
}

import scala.annotation.tailrec
import scala.collection.immutable.HashMap

/**
  * @see http://codeforces.com/contest/862/problem/B
  */

object BMahmoudAndEhabAndTheBipartiteness extends App {
  /**
    * Bicoloring based of dfs
    *
    * @param g is a connected acyclic graph
    * @return
    */
  def bicoloring(g: HashMap[Int, List[Int]]): (Long, Long) = {
    @tailrec
    def dfs(h: List[(Int, List[Int], Int)], cts: (Long, Long)): (Long, Long) = {
      if (h.isEmpty) cts
      else {
        val (u, adj, c) = h.head
        if (adj.isEmpty) dfs(h.tail, (cts._1 + c ^ 1, cts._2 + c ^ 0))
        else {
          val v = adj.head
          dfs((v, g(v).filter(p => p != u), if (c == 0) 1 else 0) :: (u, adj.tail, c) :: h.tail, cts)
        }
      }
    }

    dfs(List((1, g(1), 0)), (0L, 0L))
  }

  /**
    * 1 <= n <= math.pow(10, 5)
    */
  val n = scala.io.StdIn.readLine().toInt

  /**
    * The adjacency-list representation of a graph
    * g is a connected acyclic graph
    */
  val g = (0 until n - 1).foldLeft(new HashMap[Int, List[Int]]) { (g, _) =>
    val Array(u, v) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    g + (v -> (u :: g.getOrElse(v, Nil)), u -> (v :: g.getOrElse(u, Nil)))
  }

  val (a, b) = bicoloring(g)
  println(a * b - n + 1)
}

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

object Main{
  def main(args: Array[String]) {
    val bf = new BufferedReader(new InputStreamReader(System.in))
    val N = bf.readLine.toInt
    val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(" ")
    val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)
    val G = E groupBy(_._1) mapValues (_ map(_._2))
    def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList.toMap;
    val black = coloring.filter{case (id, color) => color == 0}.size
    val white = N - black

    println(black * white - (N - 1));
  }
}

import java.util.Scanner

object Main{
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val E = for (id <- 0 until (N - 1); p <- (sc.nextInt(), sc.nextInt) :: Nil; ps <- (p._1, p._2) :: (p._2, p._1) :: Nil) yield ps
    val G = E groupBy(_._1) mapValues (_ map(_._2))
    println(G)
    def Color(x: Int, p: Int, c: Int): Map[Int, Int] = G(x).filter(_ != p).map(Color(_, x, 1 - c)).flatten.toMap.updated(x, c)
    val coloring = Color(1, -1, 0);
    val black = coloring.filter{case (id, color) => color == 0}.size
    val white = N - black

    println(black * white - (N - 1));
  }
}