You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\frac{n}{2}$$$ opening brackets '(' and $$$\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is:  "()" is regular bracket sequence;  if $$$s$$$ is regular bracket sequence then "(" + $$$s$$$ + ")" is regular bracket sequence;  if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\frac{n}{2}$$$ opening and $$$\frac{n}{2}$$$ closing brackets.

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.

NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".

//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/C
 */
object MoveBrackets {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val n = io.StdIn.readInt()
      val s = io.StdIn.readLine().toList

      @scala.annotation.tailrec
      def loop(ls: List[Char], score: Int = 0, acc: Int = 0): Int = {
        ls match {
          case Nil => acc
          case '(' :: tail => loop(tail, score + 1, acc)
          case ')' :: tail if score == 0 => loop(tail, score, acc + 1)
          case ')' :: tail => loop(tail, score - 1, acc)
        }
      }

      println(loop(s))
    }
  }
}

import scala.io.StdIn._
import math._

object CF653_C extends App {
  val t = readInt()
  for (_ <- 0 until t) {
    val _ = readInt()
    val s = readLine()

    var delta = 0
    var max_abs_delta = 0
    for (c <- s) {
      if (c == '(') {
        delta += 1
      } else {
        delta -= 1
      }

      max_abs_delta = max(max_abs_delta, -delta)
    }

    println(max_abs_delta)
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val s = ns(n)
      var cntO = 0
      var ans = 0
      REP(n) { i =>
        if(s(i) == '(') cntO+=1
        else if(s(i) == ')' && cntO > 0) cntO -= 1
        else {
          ans+=1
        }
      }
      out.println(ans)
    }
  }

}

object C extends App {

  import scala.collection.mutable
  import scala.io.Source
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.collection.mutable.Stack
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }

  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val number     = in.nextInt()
      val input      = in.line()
      var stack      = mutable.Stack[Char]()
      var imbalanced = 0
      input.foreach(x => {
        if (x == '(') {
          stack.push(x)
        } else {
          if (stack.nonEmpty) {
            val popped = stack.pop()
            if (popped != '(') {
              imbalanced = imbalanced + 1
            }
          } else {
            imbalanced = imbalanced + 1
          }
        }
      })
      imbalanced = imbalanced + stack.length
      println(imbalanced / 2)
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

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

    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
     * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

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

}


A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter tij units of time.Order is important everywhere, so the painters' work is ordered by the following rules:  Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n);  each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on;  each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest;  as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.

The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 ≤ tij ≤ 1000), where tij is the time the j-th painter needs to work on the i-th picture.

Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.

object Main {
  def main (args: Array[String]) {
    val Array(m, n) = readLine().split(" ").map(_.toInt)
    val times = new Array[Int](n)
    val answer = for (i <- 1 to m) yield {
      val t = readLine().split(" ").map(_.toInt)
      times(0) += t(0)
      for (k <- 1 until n) {
        times(k) = max(times(k - 1), times(k)) + t(k)
      }
      times.last
    }

    print(answer(0))
    for (i <- 1 until m) {
      print(" " + answer(i))
    }
    println()
  }

  def max(x: Int, y: Int) = if (x > y) x else y
}

import java.util.Scanner

object B extends App {
  val sc = new Scanner(Console.in)
  val m = sc.nextInt()
  val n = sc.nextInt()
  val T = Array.ofDim[Int](m, n)
  val U = Array.ofDim[Int](m, n)

  for(i <- 0 until m) {
    for(j <- 0 until n) {
      T(i)(j) = sc.nextInt()
    }
  }

  U(0)(0) = T(0)(0)
  for(j <- 1 until n) {
    U(0)(j) = U(0)(j - 1) + T(0)(j)
  }

  for(i <- 1 until m) {
    U(i)(0) = T(i)(0) + U(i-1)(0)
    for(j <- 1 until n) {
      U(i)(j) = T(i)(j) + math.max(U(i-1)(j), U(i)(j-1))
    }
  }

  for(i <- 0 until m) {
    print(U(i)(n-1))
    print(" ")
  }
}

import java.util.Scanner

object B extends App {
  val sc = new Scanner(System.in)
  val m = sc.nextInt()
  val n = sc.nextInt()
  val T = Array.ofDim[Int](m, n)
  val U = Array.ofDim[Int](m, n)

  for(i <- 0 until m) {
    for(j <- 0 until n) {
      T(i)(j) = sc.nextInt()
    }
  }

  U(0)(0) = T(0)(0)
  for(j <- 1 until n) {
    U(0)(j) = U(0)(j - 1) + T(0)(j)
  }

  for(i <- 1 until m) {
    U(i)(0) = T(i)(0) + U(i-1)(0)
    for(j <- 1 until n) {
      U(i)(j) = T(i)(j) + math.max(U(i-1)(j), U(i)(j-1))
    }
  }

  for(i <- 0 until m) {
    print(U(i)(n-1))
    print(" ")
  }
}

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

  val Array(m, n) = in.next().split(' ').map(_.toInt)
  val data = (1 to m).map(_ => in.next().split(' ').map(_.toInt))
  val res = (1 until n).foldLeft(data.map(_.head).scanLeft(0){_+_}.tail) {
    case(acc, el) =>
      val master = data.map(_(el))
      var finish = 0
      master.zip(acc).map {
        case((current, previous)) =>
          finish = Math.max(previous + current, finish + current)
          finish
      }
  }
  println(res.mkString(" "))
}

object Solution extends App {
  val firstLine = readLine().split(" ").map(_.toInt)
  val m = firstLine(0) // number of paint
  val n = firstLine(1) // number of person
  val cost = new Array[Array[Int]](m)

  for(i<- 0 until m) {
    cost(i) = readLine().split(" ").map(_.toInt).toArray
  }

  val dp = new Array[Array[Int]](n)
  for(i <- 0 until n) dp(i) = new Array[Int](m)

  for(i <- 0 until n)
    for(j <- 0 until m) {
      dp(i)(j) = cost(j)(i)
      if(j > 0) dp(i)(j) = math.max(dp(i)(j), dp(i)(j - 1) + cost(j)(i))
      if(i > 0) dp(i)(j) = math.max(dp(i)(j), dp(i - 1)(j) + cost(j)(i))
    }

  println(dp(n - 1) mkString " ")

}

import java.util.Scanner

object B extends App {

val sc = new Scanner(System.in)

val n = sc.nextInt()
val m = sc.nextInt()

val in = Array.ofDim[Int](n, m)

for (i <- 0 until n) {
  for (j <- 0 until m) {
    in(i)(j) = sc.nextInt()
  }
}

val dp = new Array[Int](m)
for (i <- 0 until n) {
  for (j <- 0 until m) {
    if (j != 0)
      dp(j) = (dp(j-1) max dp(j)) + in(i)(j)
    else
      dp(j) += in(i)(j)
  }
  print(dp(m-1) + " ")
}

}


Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.

The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line.

Print a single integer — the minimum number of seconds needed to destroy the entire line.

NoteIn the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.

object B{
  //import scala.collection.mutable.PriorityQueue
  import scala.collection.mutable.ListBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val c = (for(i<-0 until n ) yield nextInt).toArray
    val ans=Array.ofDim[Int](n,n)
    for(sep<-0 until n){
      for(l<-0 until n-sep){
        val r=l+sep
        ans(l)(r)=n+1
        if(c(l)==c(r)){
          if(r-1>l+1){
            ans(l)(r)=ans(l+1)(r-1)
          }else{
            ans(l)(r)=0
          }
        }

        for(c<-l until r){

          ans(l)(r)=Math.min(ans(l)(r),1+ans(l)(c)+ans(c+1)(r))
        }

      }
    }

    out.println(ans(0)(n-1)+1)
    //code ends here
    out.flush
    out.close
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  import scala.collection.mutable.ListBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val c = (for(i<-0 until n ) yield nextInt).toArray
    val ans=Array.ofDim[Int](n,n)
    for(sep<-0 until n){
      for(l<-0 until n-sep){
        val r=l+sep
        if(c(l)==c(r)){
          if(r-1>l+1){
            ans(l)(r)=ans(l+1)(r-1)
          }else{
            ans(l)(r)=0
          }
        }else{
          ans(l)(r)=n+1
          for(c<-l until r){

            ans(l)(r)=Math.min(ans(l)(r),1+ans(l)(c)+ans(c+1)(r))
          }

        }
      }
    }

    out.println(ans(0)(n-1)+1)
    //code ends here
    out.flush
    out.close
  }
}


Two players A and B have a list of $$$n$$$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $$$\{1, 2, 2, 3\}$$$ in a list and you decided to choose $$$2$$$ for the next turn, only a single instance of $$$2$$$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.

The first line of input contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the sizes of the list. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^6$$$), describing the list of the player A, who starts the game. The third line contains $$$n$$$ integers $$$b_i$$$ ($$$1 \le b_i \le 10^6$$$), describing the list of the player B.

Output the difference between A's score and B's score ($$$A-B$$$) if both of them are playing optimally.

NoteIn the first example, the game could have gone as follows:   A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A takes his $$$1$$$.  B takes his $$$1$$$. Hence, A's score is $$$1$$$, B's score is $$$1$$$ and difference is $$$0$$$.There is also another optimal way of playing:  A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A removes $$$1$$$ from B's list.  B removes $$$1$$$ from A's list. The difference in the scores is still $$$0$$$.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $$$0$$$.

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A, B = na(N)
    radixSort(A)
    radixSort(B)

    val stack = Array.fill[mutable.Stack[Int]](2)(mutable.Stack())
    rep(N) { i =>
      stack(0).push(A(i))
      stack(1).push(B(i))
    }

    var i = 0
    val S = Array.ofDim[Long](2)
    while(stack(0).nonEmpty || stack(1).nonEmpty) {
      val me = i & 1
      val you = me ^ 1
      if (stack(me).nonEmpty && stack(you).nonEmpty) {
        if (stack(me).top < stack(you).top) {
          stack(you).pop
        } else {
          S(me) += stack(me).pop
        }

      } else if (stack(me).nonEmpty) {
        S(me) += stack(me).pop
      } else {
        stack(you).pop
      }

      i += 1
    }

//    var i = 0
//    var a, b = N - 1
//    var Sa, Sb = 0L
//    while(a > 0 || b > 0) {
//      if (i % 2 == 0) {
//        if (a > 0 && b > 0) {
//          if (A(a) < B(b)) {
//            b -= 1
//          } else {
//            Sa += A(a)
//            a -= 1
//          }
//        } else {
//          if (A(a) > B(b)) {
//            a -= 1
//          } else {
//            Sb += B(b)
//            b -= 1
//          }
//        }
//      }
//      i += 1
//    }

    out.println(S(0) - S(1))
  }

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

  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(f1: Array[Int], n: Int): Array[Int] = {
    var f = f1
    var to = Array.ofDim[Int](n)

    val b = Array.ofDim[Int](65537)
    rep(n){ i => b(1 + (f(i) & 0xffff)) += 1 }
    rep(65536, 1){ i => b(i) += b(i - 1) }
    rep(n){ i =>
      val j = f(i) & 0xffff
      to(b(j)) = f(i)
      b(j) += 1
    }
    val temp = f
    f = to
    to = temp

    java.util.Arrays.fill(b, 0)
    rep(n){ i => b(1 + (f(i) >>> 16)) += 1 }
    rep(65536, 1){ i => b(i) += b(i - 1) }
    rep(n){ i =>
      val j = f(i) >>> 16
      to(b(j)) = f(i)
      b(j) += 1
    }
    to
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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


There are $$$n$$$ left boots and $$$n$$$ right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings $$$l$$$ and $$$r$$$, both of length $$$n$$$. The character $$$l_i$$$ stands for the color of the $$$i$$$-th left boot and the character $$$r_i$$$ stands for the color of the $$$i$$$-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.

The first line contains $$$n$$$ ($$$1 \le n \le 150000$$$), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string $$$l$$$ of length $$$n$$$. It contains only lowercase Latin letters or question marks. The $$$i$$$-th character stands for the color of the $$$i$$$-th left boot. The third line contains the string $$$r$$$ of length $$$n$$$. It contains only lowercase Latin letters or question marks. The $$$i$$$-th character stands for the color of the $$$i$$$-th right boot.

Print $$$k$$$ — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following $$$k$$$ lines should contain pairs $$$a_j, b_j$$$ ($$$1 \le a_j, b_j \le n$$$). The $$$j$$$-th of these lines should contain the index $$$a_j$$$ of the left boot in the $$$j$$$-th pair and index $$$b_j$$$ of the right boot in the $$$j$$$-th pair. All the numbers $$$a_j$$$ should be distinct (unique), all the numbers $$$b_j$$$ should be distinct (unique). If there are many optimal answers, print any of them.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A, B = ns(N)

    def grouped(S: Array[Char]): Array[mutable.Stack[Int]] = {
      val C = Array.fill[mutable.Stack[Int]](27)(mutable.Stack()) // 26に?のぱしょが入っている
      REP(N) { i =>
        if (S(i) == '?') C(26).push(i)
        else C(S(i) - 'a').push(i)
      }
      C
    }

    val Ca = grouped(A)
    val Cb = grouped(B)

    DEBUG {
      REP(27) { i =>
        debugL(i)
        debug("["+Ca(i).mkString(",")+"]")
        debug("["+Cb(i).mkString(",")+"]")
      }
    }

    val ans = ArrayBuffer[(Int, Int)]()
    REP(26) { i =>
      while(Ca(i).nonEmpty && Cb(i).nonEmpty) {
        val ai = Ca(i).pop()
        val bi = Cb(i).pop()
        ans += ((ai, bi))
      }
    }

    REP(26) { i =>
      while(Ca(i).nonEmpty && Cb(26).nonEmpty) {
        val ai = Ca(i).pop()
        val bi = Cb(26).pop()
        ans += ((ai, bi))
      }
      while(Ca(26).nonEmpty && Cb(i).nonEmpty) {
        val ai = Ca(26).pop()
        val bi = Cb(i).pop()
        ans += ((ai, bi))
      }
    }
    while(Ca(26).nonEmpty && Cb(26).nonEmpty) {
      val ai = Ca(26).pop()
      val bi = Cb(26).pop()
      ans += ((ai, bi))
    }

    out.println(ans.length)
    ans.foreach { case (a, b) =>
      out.println(s"${a+1} ${b+1}")
    }
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

  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 = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def 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]) = {
    val cum = Array.ofDim[Int](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object _1141D extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    type E = (Char, Int)
    val (wildcardL, regularL), (wildcardR, regularR) = io.read[String].zip(1 to n).sorted.toList.partition(_._1 == '?')

    val unmatchedL, unmatchedR = mutable.ArrayBuffer.empty[E]
    val ans = mutable.ArrayBuffer.empty[(E, E)]

    @tailrec def loop(left: List[E], right: List[E]): Unit = (left, right) match {
      case ((l1 @ (lc, _)) :: ls, (r1 @ (rc, _)) :: rs) =>
        if (lc < rc) {
          unmatchedL += l1
          loop(ls, right)
        } else if (lc > rc) {
          unmatchedR += r1
          loop(left, rs)
        } else {
          ans += l1 -> r1
          loop(ls, rs)
        }
      case _ =>
        unmatchedL ++= left
        unmatchedR ++= right
    }

    loop(left = regularL, right = regularR)

    ans ++= unmatchedL.zip(wildcardR)
    ans ++= wildcardL.zip(unmatchedR)
    ans ++= wildcardL.drop(unmatchedR.length).zip(wildcardR.drop(unmatchedL.length))

    io.writeLine(ans.length).writeLines(ans.map({case ((_, i), (_, j)) => s"$i $j"}))
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object _1141D extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    type E = (Char, Int)
    val (wildcardL, regularL), (wildcardR, regularR) = io.read[String].zip(1 to n).sorted.toList.partition(_._1 == '?')

    val unmatchedL, unmatchedR = mutable.ArrayBuffer.empty[E]
    val ans = mutable.ArrayBuffer.empty[(E, E)]

    @tailrec
    def loop(left: List[E], right: List[E]): Unit = (left, right) match {
      case (Nil, _) => unmatchedR ++= right
      case (_, Nil) => unmatchedL ++= left

      case ((l1 @ (lc, _)) :: ls, (r1 @ (rc, _)) :: rs) =>
        if (lc < rc) {
          unmatchedL += l1
          loop(ls, right)
        } else if (lc > rc) {
          unmatchedR += r1
          loop(left, rs)
        } else {
          ans += l1 -> r1
          loop(ls, rs)
        }
    }
    loop(left = regularL, right = regularR)

    ans ++= unmatchedL.zip(wildcardR)
    ans ++= unmatchedR.zip(wildcardL)
    ans ++= wildcardR.drop(unmatchedL.length).zip(wildcardL.drop(unmatchedR.length))

    io.writeLine(ans.length).writeLines(ans.map({case ((_, i), (_, j)) => s"$i $j"}))
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears. The second line contains n digits a1, a2, ..., an (0 ≤ ai ≤ n - 1) — the sequence of active teeth: the active tooth of the i-th gear contains number ai.

In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.

NoteIn the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.

object B556 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readInts(n)
    var t = 0
    var break = false
    while(!break && t < n) {
      if(a.zipWithIndex.forall(x => x._1 == x._2)) {
        println("Yes")
        break = true
      }
      for(i <- 0 until n) {
        if(i%2 == 0){
          if(a(i) == n-1)
            a(i) = 0
          else
            a(i) += 1
        } else {
          if(a(i) == 0)
            a(i) = n-1
          else
            a(i) -= 1
        }
      }
      t += 1
    }
    if(!break) {
      println("No")
    }
  }

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

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

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

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

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

}

object _556B extends CodeForcesApp[Boolean] {
  import java.util.Scanner
  import scala.annotation.tailrec, scala.collection.mutable
  import CodeForcesApp._

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt
    val gears = List.fill(n)(nextInt)
    val rotated = for {
      (a, i) <- gears.zipWithIndex
      r =  if (i%2 == 0) 1 else -1
    } yield ((a - i)*r + n)%n
    rotated.distinct.size == 1
  }

  override def format(result: Boolean): String = if (result) "Yes" else "No"
}

abstract class CodeForcesApp[A] {
  import java.util.Scanner
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solve(scanner))
  def solve(scanner: Scanner): A
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}

object CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
  def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
}

import scala.annotation.tailrec, scala.collection.mutable
object _556B extends CodeForcesApp[Boolean] ({scanner => import scanner._, CodeForcesApp._
  val n = nextInt
  val gears = List.fill(n)(nextInt)
  val rotated = for {
    (a, i) <- gears.zipWithIndex
    r =  if (i%2 == 0) 1 else -1
  } yield ((a - i)*r + n)%n
  debug(n, gears, rotated)
  rotated.distinct.size == 1
}) {
  override def format(result: Boolean) = if (result) "Yes" else "No"
}

import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}

object CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus: Int = 1000000007
  def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
}

object _556B extends CodeForcesApp {
  import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable

  override type Input = List[Int]
  override type Output = Boolean

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt)
  }

  override def solve(input: Input) = {
    val n = input.size
    val end = List.tabulate(n)(identity)
    val zipped = (end zip input).zipWithIndex
    def rotate(clockwise: Boolean) = zipped map {
      case ((a, b), i) if (i%2 == 0) == clockwise => (a - b + n)%n
      case ((a, b), _) =>  (b - a + n)%n
    }
    val (left, right) = (rotate(clockwise = true), rotate(clockwise = false))
    left.distinct.size == 1 || right.distinct.size == 1
  }

  override def format(result: Output) = if (result) "Yes" else "No"
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  import CodeForcesApp._
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
/********************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
}
/**********************************[ lib ]************************************/
object CodeForcesApp {
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = collection.mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type ==>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None
/*******************************[ constants ]*********************************/
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
}

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

object B_310 {

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

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val line2 = readLine
    val gears = new Array[Int](n)
    for(i <- 0 until n) {
      gears(i) = line2.int
    }

    val steps = if (gears(0) == 0) 0 else n - gears(0)
    var res = true
    for(i <- 0 until n) {
      if (i % 2 == 0) {
        val value = (gears(i) + steps) % n
        if (value != i) {
          res = false
        }
      } else {
        val value = (gears(i) + n - steps) % n
        if (value != i) {
          res = false
        }
      }
    }

    val strRes = if (res) "Yes" else "No"
    println(strRes)

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

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()

  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """

"""

}

}


Zibi is a competitive programming coach. There are $$$n$$$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the $$$i$$$-th competitor will always have score $$$x_i$$$ when he codes the first task and $$$y_i$$$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are $$$m$$$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 300\,000$$$, $$$0 \le m \le 300\,000$$$) — the number of participants and the number of pairs of people who will not write a contest together. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^9 \le x_i, y_i \le 10^9$$$) — the scores which will the $$$i$$$-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both $$$x_i$$$ and $$$y_i$$$ same. Each of the next $$$m$$$ lines contain two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) — indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once.

Output $$$n$$$ integers — the sum of scores for all participants in the same order as they appear in the input.

NoteIn the first example, there will be only one team consisting of persons $$$1$$$ and $$$3$$$. The optimal strategy for them is to assign the first task to the $$$3$$$-rd person and the second task to the $$$1$$$-st person, this will lead to score equal to $$$1 + 2 = 3$$$.In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case...

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()

    val scores = new Array[(Long, Long, Long, Int)](n)

    (0 until n).foreach(i => scores(i) = {
      val (x, y) = readLongPair()
      (x, y, y - x, i)
    })

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    (0 until n).foreach(i => indexWhenSorted(scoresSorted(i)._4) = i)

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    (1 until n).foreach(i => prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2))

    val enmitites = Array.fill[List[Int]](n)(List())

    (0 until m).foreach { _ =>
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)
    }

    println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

}

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()
    val rangeN = 0 until n
    val rangeM = 0 until m

    val scores = new Array[(Long, Long, Long, Int)](n)

    rangeN.foreach(i => scores(i) = {
      val (x, y) = readLongPair()
      (x, y, y - x, i)
    })

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    rangeN.foreach(i => indexWhenSorted(scoresSorted(i)._4) = i)

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    (1 until n).foreach(i => prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2))

    val enmitites = Array.fill[List[Int]](n)(List())

    rangeM.foreach { _ =>
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)
    }

    println(rangeN.foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

}

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  //def input: Array[Long] = StdIn.readLine.split(" ").map(_.toLong)

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair() //StdIn.readLine.split(" ").map(_.toInt)

    val scores = new Array[(Long, Long, Long, Int)](n)

    var k = 0
    while (k < n) {
      scores(k) = {
        val (x, y) = readLongPair()
        (x, y, y - x, k)
      }
      k += 1
    }

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    var i = 0
    while (i < n) {
      indexWhenSorted(scoresSorted(i)._4) = i
      i += 1
    }

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    i = 1
    while (i < n) {
      prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)
      i += 1
    }

    val enmitites = Array.fill[List[Int]](n)(List())

    k = 0
    while (k < m) {
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)

      k += 1
    }

    val sb = new StringBuilder
    i = 0
    while (i < n) {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      sb.append(result + " ")
      i += 1
    }
    println(sb.toString())
  }

  //  implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {
  //
  //    import Numeric.Implicits._
  //
  //    def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)
  //
  //    def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)
  //
  //  }

}

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()

    val scores = new Array[(Long, Long, Long, Int)](n)

    var k = 0
    while (k < n) {
      scores(k) = {
        val (x, y) = readLongPair()
        (x, y, y - x, k)
      }
      k += 1
    }

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    var i = 0
    while (i < n) {
      indexWhenSorted(scoresSorted(i)._4) = i
      i += 1
    }

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    i = 1
    while (i < n) {
      prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)
      i += 1
    }

    val enmitites = Array.fill[List[Int]](n)(List())

    k = 0
    while (k < m) {
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)

      k += 1
    }

    (0 until n).view.force

    println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    //println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

  //  implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {
  //
  //    import Numeric.Implicits._
  //
  //    def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)
  //
  //    def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)
  //
  //  }

}

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()

    val scores = new Array[(Long, Long, Long, Int)](n)

    var k = 0
    while (k < n) {
      scores(k) = {
        val (x, y) = readLongPair()
        (x, y, y - x, k)
      }
      k += 1
    }

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    var i = 0
    while (i < n) {
      indexWhenSorted(scoresSorted(i)._4) = i
      i += 1
    }

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    i = 1
    while (i < n) {
      prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)
      i += 1
    }

    val enmitites = Array.fill[List[Int]](n)(List())

    k = 0
    while (k < m) {
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)

      k += 1
    }

    println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

  //  implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {
  //
  //    import Numeric.Implicits._
  //
  //    def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)
  //
  //    def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)
  //
  //  }

}

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()

    val scores = new Array[(Long, Long, Long, Int)](n)

    var k = 0
    while (k < n) {
      scores(k) = {
        val (x, y) = readLongPair()
        (x, y, y - x, k)
      }
      k += 1
    }

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    var i = 0
    while (i < n) {
      indexWhenSorted(scoresSorted(i)._4) = i
      i += 1
    }

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    i = 1
    while (i < n) {
      prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)
      i += 1
    }

    val enmitites = Array.fill[List[Int]](n)(List())

    k = 0
    while (k < m) {
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)

      k += 1
    }

    println(Stream.from(0).takeWhile(_ < n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    //println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

  //  implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {
  //
  //    import Numeric.Implicits._
  //
  //    def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)
  //
  //    def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)
  //
  //  }

}

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val (x, y) = na2(N)
    val Sx = sumL(x)
    val (from, to) = na2(M, -1)
    val sortedZ = Array.ofDim[Long](N)
    rep(N) { i =>
      sortedZ(i) = y(i) - x(i)
    }
    sort(sortedZ)
    val cumZ = Array.ofDim[Long](N + 1)
    rep(sortedZ.length) { i =>
      cumZ(i + 1) = cumZ(i) + sortedZ(i)
    }

    val hates = packUGraph(N, from, to)
    val zip = new ZippedCounter(sortedZ)
    rep(N) { i =>
      zip.add(sortedZ(i))
    }

    val ans = Array.ofDim[Long](N)
    rep(N) { i =>
      val z = y(i) - x(i)
      val nLt = zip.countLt(z)
      val nGe = zip.countGe(z)
      var hated = 0L
      hates(i) foreach { j =>
        hated += min(x(i) + y(j), x(j) + y(i))
      }
      val Sx1 = (N - 1).toLong * x(i)
      val Sx2 = Sx - x(i)
      val Sz1 = (nGe - 1).toLong * z
      val Sz2 = cumZ(nLt)
      val sum = Sx1 + Sx2 + Sz1 + Sz2 + - hated // Σ(x1 + x2 + min(z1, z2))
      ans(i) = sum
    }

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

  def sort(as: Array[Long]): Array[Long] = {
    val n = as.length
    val sorted = new java.util.PriorityQueue[Long](n)
    rep(n)(i => sorted.add(as(i)))
    rep(n)(i => as(i) = sorted.poll())
    as
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  def lowerBound(a: Array[Long], x: Long): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  class BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {
    def this(n: Int) = this(n, 0)(_ + _)

    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)

    /**
      * 0 index
      */
    def sum(i: Int): Long = {
      var x = i + 1
      var s: Long = 0
      while(x > 0) {
        s = f(s, bit(x))
        x -= x & -x
      }
      s
    }

    /**
      * 0 index
      */
    def add(i: Int, a: Long): Unit = {
      var x = i + 1
      while(x <= N) {
        bit(x) = f(bit(x), a)
        x += x & -x
      }
    }
  }

  /**
    * N + 1の範囲に分割する
    *
    * 例:
    * as = [3 5 6]
    * (, 3] => 0  (3, 5] => 1 (5, 6] => 2 (6, ) => 3
    *
    */
  class ZipperLB(as: Array[Long]) {
    def apply(x: Long): Int = {
      lowerBound(as, x)
    }
  }

  /**
    * まじめなBSTつくるの大変だからlesserThanをカウントできるだけのものを用意した
    * java.util.TreeSetじゃできない
    */
  class ZippedCounter(as: Array[Long]) {
    val n = as.length
    val zip = new ZipperLB(as)
    val bit = new BIT(n + 1) // zipされたレンジはn + 1個になる
    var cnt = 0

    /**
      * @param x 必ずレンジの上限を追加しないいけない
      */
    def add(x: Long): Unit = {
      val i = zip(x)
      assert(i < n && x == as(i))
      bit.add(i, 1)
      cnt += 1
    }

    def countLt(x: Long): Int = {
      // レンジの上限の値しか存在しないので、ある値より小さい = より小さいレンジ と置き換えることができる
      val i = zip(x)
      if (i > 0) bit.sum(i - 1).toInt
      else 0
    }

    def countLe(x: Long): Int = {
      countLt(x + 1)
    }

    def countGe(x: Long): Int = {
      cnt - countLt(x)
    }

    def countGt(x: Long): Int = {
      cnt - countLe(x)
    }
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def 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 nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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


Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!Let us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one.Rikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left.One problem with prime numbers is that there are too many of them. Let's introduce the following notation: π(n) — the number of primes no larger than n, rub(n) — the number of palindromic numbers no larger than n. Rikhail wants to prove that there are a lot more primes than palindromic ones.He asked you to solve the following problem: for a given value of the coefficient A find the maximum n, such that π(n) ≤ A·rub(n).

The input consists of two positive integers p, q, the numerator and denominator of the fraction that is the value of A (, ).

If such maximum number exists, then print it. Otherwise, print "Palindromic tree is better than splay tree" (without the quotes).

import scala.collection._

object A extends App {

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

  val Array(p, q) = readInts(2)

  def isPalindrome(_x: Int) = {
    var rev = 0
    var x = _x
    while (x > 0) {
      rev = rev * 10 + (x % 10)
      x /= 10
    }
    rev == _x
  }

  val LIMIT = 20000000
  val prime = Array.fill(LIMIT)(true)
  prime(0) = false
  prime(1) = false

  Stream.from(2).takeWhile(i => i * i < LIMIT).filter(prime(_)).foreach { i =>
    (i * i until LIMIT by i).foreach(prime(_) = false)
  }

  var n = 1
  var res = 1
  var cntPrime, cntPal = 0L
  while (cntPrime * q <= cntPal * p || n < LIMIT) {
    if (cntPrime * q <= cntPal * p) res = n - 1
    if (isPalindrome(n)) cntPal += 1
    if (prime(n)) cntPrime += 1
    //println(n, cntPal, cntPrime, cntPrime * q, cntPal * p)
    n += 1
  }

  println(res)

}


A sequence $$$a_1, a_2, \dots, a_n$$$ is called good if, for each element $$$a_i$$$, there exists an element $$$a_j$$$ ($$$i \ne j$$$) such that $$$a_i+a_j$$$ is a power of two (that is, $$$2^d$$$ for some non-negative integer $$$d$$$).For example, the following sequences are good:  $$$[5, 3, 11]$$$ (for example, for $$$a_1=5$$$ we can choose $$$a_2=3$$$. Note that their sum is a power of two. Similarly, such an element can be found for $$$a_2$$$ and $$$a_3$$$),  $$$[1, 1, 1, 1023]$$$,  $$$[7, 39, 89, 25, 89]$$$,  $$$[]$$$. Note that, by definition, an empty sequence (with a length of $$$0$$$) is good.For example, the following sequences are not good:  $$$[16]$$$ (for $$$a_1=16$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two),  $$$[4, 16]$$$ (for $$$a_1=4$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two),  $$$[1, 3, 2, 8, 8, 8]$$$ (for $$$a_3=2$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two). You are given a sequence $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.

The first line contains the integer $$$n$$$ ($$$1 \le n \le 120000$$$) — the length of the given sequence. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $$$n$$$ elements, make it empty, and thus get a good sequence.

NoteIn the first example, it is enough to delete one element $$$a_4=5$$$. The remaining elements form the sequence $$$[4, 7, 1, 4, 9]$$$, which is good.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val set = mutable.Map[Long, Int]().withDefaultValue(0)
    REP(N) { i =>
      set(A(i)) = set(A(i)) + 1
    }

    val MAX = 32
//    val MAX = 4

    val ans = map(N)(identity).count { i =>
      val ok = map(MAX)(identity).exists { k =>
        val b = (2L << k) - A(i)
        if (b == A(i))
          set(b) > 1
        else
          b > 0 && set.contains(b)
      }
//      System.err.println(s"${A(i)} $ok")
      !ok
    }

    out.println(ans)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

import scala.collection.mutable._

object Solution {

  def solve(ls: List[Int]): Int = {
    var f = new HashMap[Int, Int]()
    ls.foreach(x => {
      f.get(x) match {
        case Some(y) => f += (x -> (y+1))
        case None => f += (x -> 1)
      }
    })

    var cnt = 0

    val p2 = (0 to 31).toList.map(x => 1 << x)
    ls.foreach(x => {
      val hasComplement = p2.foldLeft(false) { (acc, b) => {
          val v = f.get(b-x) match {
            case Some(y) => {
              if (b-x == x) {
                if (y > 1) true
                else false
              } else true
            }
            case None => false
          }
          acc || v
        }

      }
      if (!hasComplement) cnt += 1
    })

    cnt
  }

  def main(args: Array[String]) {
    val t = io.StdIn.readLine
    val ls = io.StdIn.readLine.split(" ").map(_.toInt).toList
    println(solve(ls))
  }
}

import scala.collection.mutable
import scala.io.StdIn

object Codeforces1005C {

  def getMinimumRemoveForBeingGood(elements: Array[Int]): Int = {
    val powers = (0 to 33).map(power => 1L << power)

    val elementMatchMap = new mutable.HashMap[Long, Data]()

    elements.foreach(element => {
      if (elementMatchMap.contains(element)) {
        elementMatchMap(element).frequency += 1
      } else {
        elementMatchMap.put(element, new Data(1, false))
      }
    })

    for (element <- elementMatchMap.keySet) {
      powers
        .map(p => p - element)
        .filter(e => elementMatchMap.contains(e))
        .filter(e => e != element || elementMatchMap(e).frequency != 1)
        .foreach(matchedElement => {
          elementMatchMap(element).hasMatched = true
          elementMatchMap(matchedElement).hasMatched = true
        })
    }

    var misMatchCount = 0
    for ((_, data) <- elementMatchMap) {
      if (!data.hasMatched)
        misMatchCount += data.frequency
    }
    misMatchCount
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val elements = StdIn.readLine.split(" ").map(_.trim.toInt)
    val result = getMinimumRemoveForBeingGood(elements)
    println(result)
  }

  class Data(var frequency: Int, var hasMatched: Boolean)

}