You are given two integers $$$n$$$ and $$$m$$$. You have to construct the array $$$a$$$ of length $$$n$$$ consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly $$$m$$$ and the value $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ is the maximum possible. Recall that $$$|x|$$$ is the absolute value of $$$x$$$.In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $$$a=[1, 3, 2, 5, 5, 0]$$$ then the value above for this array is $$$|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$$$. Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the length of the array and its sum correspondingly.

For each test case, print the answer — the maximum possible value of $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ for the array $$$a$$$ consisting of $$$n$$$ non-negative integers with the sum $$$m$$$.

NoteIn the first test case of the example, the only possible array is $$$[100]$$$ and the answer is obviously $$$0$$$.In the second test case of the example, one of the possible arrays is $$$[2, 0]$$$ and the answer is $$$|2-0| = 2$$$.In the third test case of the example, one of the possible arrays is $$$[0, 2, 0, 3, 0]$$$ and the answer is $$$|0-2| + |2-0| + |0-3| + |3-0| = 10$$$.

//package codeforces.contests._1353

object MostUnstableArray {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)
      println {
        n match {
          case 1 => 0
          case 2 => m
          case _ => 2L * m
        }
      }
    }
  }

}

import scala.io.StdIn.readLine

object A {

  def solution(n: Int, m: Int): Int = n match {
    case 1 => 0
    case 2 => m
    case _ => 2 * m
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(n, m) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(n, m))
    }
  }
}

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

import scala.math.max
import scala.math.min
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("problem.in"))),
						new PrintWriter(new File("problem.out"))
					)
				}
			new CF644(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 CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {

	import Main._
	import fScanner._

	// def solve(): Unit = {
	// 	val T = ni()
	// 	for(i <- 0 until T){
	// 	var ans : Int = 1000
	// 		val n = ni()
	// 		var list: List[Int] = List()
	// 		for(j <- 0 until n){
	// 			val cu:Int = ni()
	// 			for( x <- list)
	// 				ans = ans.min( ( cu - x ).max(x - cu) )
	// 			list = cu::	list
	// 		}
	// 		out.println(ans)
	// 	}
	// }

	def solve(): Unit ={
		val T = ni()
		for(i <- 0 until T){
			val n = ni()
			val m = ni()
			n match {
				case 1 =>
					out.println(0)
				case 2 =>
					out.println(m)
				case _ =>
					out.println(2*m)
			}
		}
	}
}

object A extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val r =
      if (n == 1) 0
      else if (n == 2) m
      else 2 * m

    println(r)
  }
}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val m = in.nextInt()

    if (n == 1) {
      println(0)
    } else if (n == 2) {
      println(m)
    } else {
      println(m * 2)
    }

  }

}

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

import scala.math.max
import scala.math.min
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("problem.in"))),
						new PrintWriter(new File("problem.out"))
					)
				}
			new CF644(in, out).solve()
			out.flush()
			out.close()
		} catch {
			case e: IOException => e.printStackTrace()
		}
	}

	private[this] val isOnlineJudge = false

	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 CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {

	import Main._
	import fScanner._

	// def solve(): Unit = {
	// 	val T = ni()
	// 	for(i <- 0 until T){
	// 	var ans : Int = 1000
	// 		val n = ni()
	// 		var list: List[Int] = List()
	// 		for(j <- 0 until n){
	// 			val cu:Int = ni()
	// 			for( x <- list)
	// 				ans = ans.min( ( cu - x ).max(x - cu) )
	// 			list = cu::	list
	// 		}
	// 		out.println(ans)
	// 	}
	// }

	def solve(): Unit ={
		val T = ni()
		for(i <- 0 until T){
			val n = ni()
			val m = ni()
			n match {
				case 1 =>
					out.println(0)
				case 2 =>
					out.println(m)
				case _ =>
					out.println(2*m)
			}
		}
	}
}

object A extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val c = n / 2

    val r =
      if (c == 0) 0
      else if (c == 1) m
      else 2 * m

    println(r)
  }
}

object A extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val c = n / 2

    val r =
      if (c == 0) 0
      else if (c == 1) m
      else {
        val ai = m / c
        val a1 = m - ai * (c - 1)

        if (n % 2 == 0) (a1 + ai) * 2 + ai * 2 * (c - 2)
        else a1 * 2 + ai * 2 * (c - 1)
      }

    println(r)
  }
}


Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were $$$n$$$ classes of that subject during the semester and on $$$i$$$-th class professor mentioned some non-negative integer $$$a_i$$$ to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $$$a$$$ to help out students like Mishka:   $$$a$$$ was sorted in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$);  $$$n$$$ was even;  the following sequence $$$b$$$, consisting of $$$\frac n 2$$$ elements, was formed and given out to students: $$$b_i = a_i + a_{n - i + 1}$$$. Professor also mentioned that any sequence $$$a$$$, which produces sequence $$$b$$$ with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence $$$a$$$ of non-negative integers, which produces sequence $$$b$$$ with the presented technique. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of sequence $$$a$$$. $$$n$$$ is always even. The second line contains $$$\frac n 2$$$ integers $$$b_1, b_2, \dots, b_{\frac n 2}$$$ ($$$0 \le b_i \le 10^{18}$$$) — sequence $$$b$$$, where $$$b_i = a_i + a_{n - i + 1}$$$. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

Print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{18}$$$) in a single line. $$$a_1 \le a_2 \le \dots \le a_n$$$ should be satisfied. $$$b_i = a_i + a_{n - i + 1}$$$ should be satisfied for all valid $$$i$$$.

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 B = nal(N / 2)
    val A = Array.ofDim[Long](N)
    var l = 0L
    var r = 1e18.toLong + 9
    REP(N / 2) { i =>
      val b = B(i)

      val l0 = l
      val r0 = b - l0
      if (r0 <= r) {
        l = l0
        r = r0
      } else {
        l = b - r
      }

      A(i) = l
      A(N - 1 - i) = r
    }

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

  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.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn

object MishkaAndTheLastExam extends App {

  val n = StdIn.readLine().toInt

  println(createA(StdIn.readLine().split(" ").map(_.toLong)))

  def createA(half: Array[Long]): String = {
    val left = mutable.ArrayStack[Long]()
    val right = mutable.ArrayStack[Long]()

    half.foreach(solutionForIth(_, left, right))

    left.reverse.mkString(" ") + " " + right.mkString(" ")
  }

  def solutionForIth(ith: Long, left: mutable.ArrayStack[Long], right: mutable.ArrayStack[Long]) = {

    @tailrec
    def sol(li: Long, ri: Long): Unit = {
      if (left.isEmpty) {
        left.push(li)
        right.push(ri)
        return
      }

      val rtop = right.top
      val ltop = left.top

      if (rtop >= ri && ltop <= li) {
        left.push(li)
        right.push(ri)
        return
      }

      val diff = if (ri > rtop) {
        ri - rtop
      } else {
        ltop - li
      }

      sol(li + diff, ri - diff)
    }

    sol(0, ith)
  }
}

object C 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(n) = readInts(1)
  val bs = readLongs(n / 2)
  val as = Array.ofDim[Long](n)

  var l = 0L
  var r = Long.MaxValue

  for (i <- 0 until n / 2) {
    var l2 = l
    var r2 = bs(i) - l2
    if (r2 >= r) {
      r2 = r
      l2 = bs(i) - r2
    }
    as(i) = l2
    as(n - i - 1) = r2
    l = l2
    r = r2
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(as.mkString(" "))
  Console.flush
}

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

object MishkaAndTheLastExam extends App {

  val n = StdIn.readLine().toInt

  println(createA(StdIn.readLine().split(" ").map(_.toLong)))

  def createA(half: Array[Long]): String = {
    val left = mutable.ArrayStack[Long]()
    val right = mutable.ArrayStack[Long]()

    half.foreach(solutionForIth(_, left, right))

    left.reverse.mkString(" ") + " " + right.mkString(" ")
  }

  def solutionForIth(ith: Long, left: mutable.ArrayStack[Long], right: mutable.ArrayStack[Long]) = {

    def sol(li: Long, ri: Long): Unit = {
      if (left.isEmpty) {
        left.push(li)
        right.push(ri)
        return
      }

      val rtop = right.top
      val ltop = left.top

      if (left.nonEmpty && rtop >= ri && ltop <= li) {
        left.push(li)
        right.push(ri)
        return
      }

      if (ri > rtop) {
        sol(li + 1, ri - 1)
      }

    }

    sol(0, ith)
  }
}


After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.

The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.  The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.

Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.

object CF297A extends App {
  import scala.collection.mutable.HashMap
  import scala.io.{StdIn}

  val n: Int = StdIn.readInt()
  val keysAndRooms: String = StdIn.readLine()
  var acc = 0

  keysAndRooms.toIterable.foreach(solve(new Multiset[Char]))

  print (acc)

  def solve(multiset: Multiset[Char]): (Char) => Unit = {
    (ch: Char) => {
      if(ch.isLower){
        multiset.add(ch.toUpper)
      } else {
        if(multiset.contains(ch)){
          multiset.remove(ch)
        } else{
          acc = acc + 1
        }
      }
    }
  }

  class Multiset[T] {
    val hashMap = new HashMap[T, Int]()

    def add(element: T) = {
      val count = hashMap.getOrElseUpdate(element, 0)
      hashMap+=((element, count+1))
    }

    def contains(element:T ) = {
      hashMap.get(element).nonEmpty
    }

    def remove(element: T) = {
      val count = hashMap.getOrElse(element, 1)
      if (count == 1) {
        hashMap.remove(element)
      } else {
        hashMap+=((element, count-1))
      }
    }
  }

}

object Solution extends App {

  readInt()

  var key: Int = 0
  readLine().foldLeft(Map.empty[Char, Int]){
    case (acc, el) if el.isLower => acc + (el -> (acc.getOrElse(el, 0) + 1))
    case (acc, el) =>
      val lower = el.toLower
      val newValue = acc.getOrElse(lower, 0) - 1
      if (newValue >= 0)
        acc + (lower -> (acc.getOrElse(lower, 0) - 1))
      else {
        key += 1
        acc
      }
  }
  println(key)
}

object A525 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = read
    val keys = Array.fill(26)(0)
    var res = 0
    for(i <- 0 until n-1) {
      val k = 2*i
      keys(in(k)-'a') += 1
      val d = 2*i + 1
      if(keys(in(d).toLower-'a') > 0) {
        keys(in(d).toLower-'a') -= 1
      } else {
        res += 1
      }
    }
    println(res)
  }

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

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

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

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

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

}

import scala.collection.mutable

/**
 * Created by yangchaozhong on 3/27/15.
 */
object CF525A extends App {
  import scala.collection.mutable.{HashMap}

  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val s = nextString
    val map = HashMap[Char, Int]()
    var count = 0
    (1 to (n - 1)).foreach { i =>
      val l = s(i * 2 - 2)
      val r = s(i * 2 - 1).toLower
      if (l != r) {
        if (map.contains(l)) {
          map(l) += 1
        } else {
          map(l) = 1
        }

        if (map.contains(r) && map(r) > 0) {
          map(r) -= 1
        } else {
          count += 1
        }
      }
    }

    out.println(count)
  }

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

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

import scala.collection.mutable

object A {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val map = next.toCharArray
    val size = 2 * n - 2
    val keys = new MultiHashSet[Char]()
    var ans = 0
    for (i <- 0 until size by 2) {
      keys.add(map(i).toUpper)
      if (keys.count(map(i + 1)) > 0) {
        keys.remove(map(i + 1))
      } else {
        ans += 1
      }
    }
    out.println(ans)
    return 0
  }
}

import java.util.Scanner

import scala.collection.mutable

object _525_A extends App {
  lazy val file = getClass.getResourceAsStream(s"${getClass.getSimpleName.head.toString}.in")
  val in = if (submit) new Scanner(System.in) else new Scanner(file)
  while(in.hasNext) {
    println(apply(parseInput))
  }
  /********************************************************************************************************************/
  def submit = true        // THIS MUST BE TRUE WHEN YOU SUBMIT

  type Input = String

  def parseInput: Input = {
    import in._
    nextInt()
    next()
  }

  def apply(line: String) = {
    val keys = mutable.Map.empty[Char, Int] withDefaultValue 0
    var ans = 0
    for {
      element <- line.grouped(2)
      (key, door) = (element(0), element(1))
    } {
      keys(key) = keys(key) + 1
      val requiredKey = door.toLower
      if (keys(requiredKey) > 0) {
        keys(requiredKey) = keys(requiredKey) - 1
      } else {
        ans += 1
      }
    }
    ans
  }
}

import scala.io.StdIn

/**
 * Created by pol on 29/03/15.
 */
object CR297_A extends App {
  val n = StdIn.readInt()
  val s = StdIn.readLine()
  var ans = 0

  var cnt = new Array[Int](255)
  for (i <- 0 until 2 * n - 2) {
    val si = s.charAt(i)
    if (si.isLower) {
      cnt(si) += 1
    } else {
      if (cnt(si.toLower) > 0) {
        cnt(si.toLower) -= 1
      } else {
        ans += 1
      }

    }
  }
  println(ans)
}

object A{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  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 keys=Array.fill(26)(0)
    val S=nextString
    var count=0
    for(i<-0 until n-1){
      val ki=S(2*i)-'a'
      val Di=S(2*i+1)-'A'
      keys(ki)+=1
      if(keys(Di)>0){
        keys(Di)-=1
      }else{
        count+=1
      }
    }
    out.println(count)
    //code ends here
    out.flush
    out.close
  }
}

object CodeForces extends App {

  def solve = {
    val n = readLine().toInt
    val doorsAndKeys = readLine().toCharArray

    var doorkeyHash = Array.fill[Int](26)(0)
    var keysRequired = 0

    def charHash(c : Char) = c.toLower - 'a'

    for (i <- 0 until 2 * n - 2) {
      val dkHash = charHash(doorsAndKeys(i))
      if (i % 2 == 0) {
        doorkeyHash(dkHash) += 1
      } else {
        if (doorkeyHash(dkHash) > 0) doorkeyHash(dkHash) -= 1
        else keysRequired += 1
      }
    }
    println(keysRequired)
  }

  solve
}

object CodeForces extends App {

  def solve = {
    val n = readLine toInt
    val doorsAndKeys = readLine

    var doorkeyHash = Array.fill[Int](26)(0)

    def charHash(c : Char) = c.toLower - 'a'

    var index = 0
    println(doorsAndKeys.foldLeft(0)((kReq, c) => {
      val dkHash = charHash(doorsAndKeys(index))
      val dkStat = if (index % 2 == 0) 1 else if (doorkeyHash(dkHash) > 0) -1 else 0
      index += 1
      doorkeyHash(dkHash) += dkStat
      kReq + (if (dkStat == 0) 1 else 0)
    }))
  }

  solve
}

/**
 * Created by yangchaozhong on 3/27/15.
 */
object CF525A extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val s = nextString

    val count = (1 to (n - 1)).map(_ * 2).count(i => s(i - 2) != s(i - 1).toLower)
    out.println(count)
  }

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


Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.

The single line contains a single integer n (n is even, 2 ≤ n ≤ 100) — the number of Gerald's brothers.

Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers — the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order.  It is guaranteed that the solution exists at the given limits.

NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.

import scala.io.StdIn._

object CF_334A_CandyBags {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val sqn = n * n
    println((((1 to sqn / 2) zip (sqn / 2 + 1 to sqn).reverse)
      .grouped(n / 2)
      .map(_.flatMap(_.productIterator).mkString(" "))).mkString("\n"))
  }
}

object P334A {

  def main(argv: Array[String]) {
    val n = readLine.toInt
    val n2 = n * n
    (0 until n).map(index =>
      println(
	((n * index) / 2 + 1 until (n * (index + 1)) / 2 + 1).foldLeft(
	  List[Int]())((lst, i) => i :: n2 - i + 1 :: lst).mkString(" ")))
  }
}

object CF334A {
    def main(argv: Array[String]) {
        val n = readLine.toInt
        def output(index: Int): Unit = {
            val a = index
            val b = n * n - index + 1
            if (index % (n >> 1) == 0) {
                if (index == (n * n) >> 1) {
                    println(a + " " + b)
                } else {
                    println(a + " " + b)
                    output(index + 1)
                }
            } else {
                print(a + " " + b + " ")
                output(index + 1)
            }
        }
        output(1)
    }
}

object A_CandyBags extends App {
  val n = readLine toLong

  import Ordering.Implicits._, Numeric.Implicits._

  def find[N](k: N, remains: Map[N, (N, List[N])])(implicit num: Numeric[N]): Map[N, List[N]] =
    if (k == num.zero)
      if (remains forall (_._2._1 == num.zero)) remains map {case (i, (r, l)) => (i, l)}
      else throw new ArithmeticException("Not found")
    else remains maxBy (_._2._1) match {
      case (i, (r, l)) if r >= k => find(k - num.one, remains updated(i, (r - k, k :: l)))
      case _ => throw new ArithmeticException("Shit happened k = " + k + " and remains are" + remains)
    }

  find[Long](n * n, 1L to n map (i => (i, (n * (n * n + 1) / 2, Nil))) toMap) map {_._2 mkString " "} foreach println
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  Range(1, n + 1).foreach { i =>
    println((Range(i, n * n / 2 + 1, n).toList ::: Range(n * n - i + 1, n * n / 2, -n).toList).mkString(" "))
  }
}

object CandyBags {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    // val n = 2
    val res = distribute(n)
    res.map(list => list.mkString(" ")).foreach(println)
  }

  def distribute(n: Int): Seq[Seq[Int]] = {
    (0 until n).map(i => (0, i)).map { case (i, j) =>
      for {
        k <- 0 until n
      } yield(get(i + k, j + k, n))
    }
  }

  def get(x: Int, y: Int, n: Int): Int = {
    val (mx, my) = (x % n, y % n)
    mx * n + my + 1
  }
}

object A334 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    var num = 1
    for(_ <- 1 to n) {
      for(_ <- 1 to n/2) {
        print(num + " ")
        print((n*n)-num+1 + " ")
        num += 1
      }
      println("")
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

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

 type Bags = List[Int]

  val bags: Bags = List(
      List.range(1, N * N / 2 + 1),
      List.range(N * N / 2 + 1, N * N + 1).reverse
    ).transpose.flatten

  def solve(): Unit = {

    @tailrec
    def loop(acc: List[Bags], bags: Bags): List[Bags] = {
      if (bags.isEmpty) acc
      else loop((bags take N) :: acc, bags drop N)
    }

    loop(List.empty[Bags], bags).foreach { xs =>
      out.println(xs.mkString(" "))
    }
  }

  solve
  out.close
}

import scala.io.StdIn._

object CandyBags extends App {

  def printCandy(line: Int, col: Int): Unit = {
    val st = (col - 1) * n + 1
    val of = (line + col) % n
    print(st + of)
    print(" ")
    if(col != n) {
      printCandy(line, col + 1)
    } else if(line != n) {
      print("\n")
      printCandy(line + 1, 1)
    }
  }

  val n = readInt
  printCandy(1, 1)

}

import annotation.tailrec
import java.io._

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

  val n = readInt
  val k = n / 2
  def ans = ((1 to n * n).take(2 * k * k) zip (1 to n * n).drop(2 * k * k).reverse).flatMap(_.productIterator).grouped(n).map(_.mkString(" ")).mkString("\n")

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

object Main {
  def c_split(n: Int) = if (n % 2 == 1) {
    (1 to n).map{ i =>
      (1 to n).map{ j =>
        1 + (((i - j + (n - 1) / 2) + n) % n ) * n + ((i + j + (n + 1) / 2) % n)
      }
    }
  } else {
    (0 until n).map{ i =>
      (0 until n / 2).flatMap { j =>
        Seq(n * n - i * (n / 2) - j, i * (n / 2) + j + 1)
      }
    }
  }

  def main(args: Array[String]) {
    val n = readInt()
    c_split(n).foreach(tr => println(tr.mkString(" ")))
  }
}

import Array._

object main extends App with fastIO {

  val n = nextInt
  var a = ofDim[Int](n, n)

  for (i <- 0 until n) if ((i & 1) == 0)
    for (j <- 0 until n) a(j)(i) = i * n + j + 1 else
    for (j <- n - 1 to (0, -1)) a(j)(i) = i * n + n - j

  for (i <- 0 until n) println(a(i).mkString(" "))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

import Array._

object main extends App with fastIO {

  val n = nextInt
  var a = ofDim[Int](n, n)

  var value = 1
  for (i <- 0 until n) {
    if ((i & 1) == 0)
    for (j <- 0 until n) {
      a(j)(i) = value
      value += 1
    } else
    for (j <- n - 1 to (0, -1)) {
      a(j)(i) = value
      value += 1
    }
  }

  for (i <- 0 until n) println(a(i).mkString(" "))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

object runner {
def main(args:Array[String]){
var liner=readInt();
var array=Array.ofDim[Int](liner,liner);
var result="";
for(i<-0 to liner-1){
  for(j<-0 to liner-1){
    if(i%2==1){
      array(i)(j)=(liner)*(i+1)-j;
    }else{
      array(i)(j)=(liner*i)+j+1;
    }
  }
}
for(t<-0 to liner-1){
  for(l<-0 to liner-1){
    result+=array(l)(t).toString+" ";
  }
  result+="\n";
}
println(result);
}
}

object Main {
  def c_split(n: Int) = if (n % 2 == 1) {
    (1 to n).map{ i =>
      (1 to n).map{ j =>
        1 + (((i - j + (n - 1) / 2) + n) % n ) * n + ((i + j + (n + 1) / 2) % n)
      }
    }
  } else {
    (1 to n).map{ i =>
      (1 to n / 2).flatMap { j =>
        Seq(n * n - i * (n / 2) - j, i * (n / 2) + j)
      }
    }
  }

  def main(args: Array[String]) {
    val n = readInt()
    c_split(n).foreach(tr => println(tr.mkString(" ")))
  }
}

object Main {
  def c_split(n: Int) = if (n % 2 == 1) {
    (1 to n).map{ i =>
      (1 to n).map{ j =>
        1 + (((i - j + (n - 1) / 2) + n) % n ) * n + ((i + j + (n + 1) / 2) % n)
      }
    }
  } else {
    (1 to n).map{ i =>
      (1 to n / 2).flatMap { j =>
        Seq(n * n - i * (n / 2) - j, i * (n / 2) + j + 1)
      }
    }
  }

  def main(args: Array[String]) {
    val n = readInt()
    c_split(n).foreach(tr => println(tr.mkString(" ")))
  }
}


You are given two arrays of length $$$n$$$: $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$.You can perform the following operation any number of times:   Choose integer index $$$i$$$ ($$$1 \le i \le n$$$);  Swap $$$a_i$$$ and $$$b_i$$$. What is the minimum possible sum $$$|a_1 - a_2| + |a_2 - a_3| + \dots + |a_{n-1} - a_n|$$$ $$$+$$$ $$$|b_1 - b_2| + |b_2 - b_3| + \dots + |b_{n-1} - b_n|$$$ (in other words, $$$\sum\limits_{i=1}^{n - 1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$$$) you can achieve after performing several (possibly, zero) operations?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 4000$$$) — the number of test cases. Then, $$$t$$$ test cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 25$$$) — the length of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) — the array $$$b$$$.

For each test case, print one integer — the minimum possible sum $$$\sum\limits_{i=1}^{n-1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$$$.

NoteIn the first test case, we can, for example, swap $$$a_3$$$ with $$$b_3$$$ and $$$a_4$$$ with $$$b_4$$$. We'll get arrays $$$a = [3, 3, 3, 3]$$$ and $$$b = [10, 10, 10, 10]$$$ with sum $$$3 \cdot |3 - 3| + 3 \cdot |10 - 10| = 0$$$.In the second test case, arrays already have minimum sum (described above) equal to $$$|1 - 2| + \dots + |4 - 5| + |6 - 7| + \dots + |9 - 10|$$$ $$$= 4 + 4 = 8$$$.In the third test case, we can, for example, swap $$$a_5$$$ and $$$b_5$$$.

import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // =====================================

  def recur(a: Array[Int], b: Array[Int], x: Long, y: Long): Long = {
    if (a.isEmpty) 0
    else {
      val ah = a.head
      val bh = b.head
      val (low, high) = if (ah < bh) (ah, bh) else (bh, ah)
      Math.abs(x - low) + Math.abs(y - high) + recur(a.tail, b.tail, low, high)
    }
  }
  def solve() = {
    val n = readLine.toInt
    val a = rsi
    val b = rsi

    val ah = a.head
    val bh = b.head

    val at = a.tail
    val bt = b.tail

    if (ah < bh) recur(at, bt, ah, bh)
    else recur (at, bt, bh, ah)
  }

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

    val cases = readLine.toInt
    for (
      i <- 0 until cases
    ) println(solve())
  }
}

import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // =====================================

  def recur(a: Array[Int], b: Array[Int], x: Int, y: Int): Int = {
    if (a.isEmpty) 0
    else {
      val ah = a.head
      val bh = b.head
      val (low, high) = if (ah < bh) (ah, bh) else (bh, ah)
      Math.abs(x - low) + Math.abs(y - high) + recur(a.tail, b.tail, low, high)
    }
  }
  def solve() = {
    val n = readLine.toInt
    val a = rsi
    val b = rsi

    val ah = a.head
    val bh = b.head

    val at = a.tail
    val bt = b.tail

    if (ah < bh) recur(at, bt, ah, bh)
    else recur (at, bt, bh, ah)
  }

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

    val cases = readLine.toInt
    for (
      i <- 0 until cases
    ) println(solve())
  }
}


Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges.

The first line of input contains two integers n and m (1 ≤ n ≤ 19, 0 ≤ m) – respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1 ≤ a, b ≤ n, a ≠ b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices.

Output the number of cycles in the given graph.

NoteThe example graph is a clique and contains four cycles of length 3 and three cycles of length 4.

//package me.jetblack.tspdp

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object MyDpCycles1 extends App {

  val s = new Scanner(System.in)

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

  val dp = Array.ofDim[Long](1 << n, n)

  val ee = Array.ofDim[Boolean](n, n)

  (0 until m).map { _ =>
    val a = s.nextInt() - 1
    val b = s.nextInt() - 1
    ee(a)(b) = true
    ee(b)(a) = true
  }

  def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0

  def first(x: Int): Int = {
    var a = x
    var cnt = 0
    while ((a & 1) == 0) {
      a = a >> 1
      cnt += 1
    }
    cnt
  }

  def count(x: Int): Int = {
    var a = x
    var cnt = 0
    while (a > 0) {
      if ((a & 1) == 1) cnt += 1
      a = a >> 1
    }
    cnt
  }

  def cnt1(x: Int): Boolean = ((x & (x - 1)) == 0 && (x != 0))

  def hasEdge(a: Int, b: Int): Boolean = {
    ee(b)(a) == 1
  }

  var acc = 0L

  (0 until n) foreach (i => dp(1 << i)(i) = 1)

  /*for {
    mask <- (1 until (1 << n))
    i <- 0 until n
  } yield {*/

  var mask = 1
  var i = 0

  while (mask < (1 << n)) {
    while (i < n) {
      val xored = mask ^ (1 << i)
      if (bit(mask, i) && !cnt1(mask) && first(mask) != i) {
        var j = 0
        while (j < n) {
          if (ee(i)(j)) {
            dp(mask)(i) += dp(xored)(j)
            if (bits(mask) >= 3 && ee(first(mask))(i))
              acc += dp(xored)(j)
          }
          j += 1
        }
      }
      i += 1
    }
    i = 0
    mask += 1
  }

  def bits(j: Int): Int = {
    var i = j
    i = i - ((i >> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
    (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
  }

  println(acc / 2)

}

//package me.jetblack.tspdp

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object MyDpCycles1 extends App {

  val s = new Scanner(System.in)

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

  val dp = Array.ofDim[Int](1 << n, n)

  val ee = Array.ofDim[Boolean](n, n)

  //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))

  (0 until m).map { _ =>
    val a = s.nextInt() - 1
    val b = s.nextInt() - 1
    ee(a)(b) = true
    ee(b)(a) = true
  }

  def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0

  def first(x: Int): Int = {
    var a = x
    var cnt = 0
    while ((a & 1) == 0) {
      a = a >> 1
      cnt += 1
    }
    cnt
  }

  def count(x: Int): Int = {
    var a = x
    var cnt = 0
    while (a > 0) {
      if ((a & 1) == 1) cnt += 1
      a = a >> 1
    }
    cnt
  }

  def cnt1(x: Int): Boolean = ((x & (x - 1)) == 0 && (x != 0))

  def hasEdge(a: Int, b: Int): Boolean = {
    ee(b)(a) == 1
  }

  var acc = 0L

  (0 until n) foreach (i => dp(1 << i)(i) = 1)

  for {
    mask <- (1 until (1 << n))
    i <- 0 until n
  } yield {
    val xored = mask ^ (1 << i)
    if (bit(mask, i) && !cnt1(mask) && first(mask) != i) {
      var j = 0
      while (j < n) {
        if (ee(i)(j)) {
          dp(mask)(i) += dp(xored)(j)
          if (bits(mask) >= 3 && ee(first(mask))(i))
            acc += dp(xored)(j)
        }
        j += 1
      }
    }
  }

  def bits(j: Int): Int = {
    var i = j
    i = i - ((i >> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
    (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
  }

  println(acc / 2)

}

//package me.jetblack.tspdp

import java.util.Scanner

object MyDpCycles extends App {

  val n = 4
  val m = 6

  val s = new Scanner(System.in)

  val dp = Array.ofDim[Long](1 << n, n)

  //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))

  val edges = (0 until m + 1).map(_ => (s.nextInt(), s.nextInt())).drop(1)

  def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0

  def first(x: Int): Int = {
    var a = x
    var cnt = 0
    while ((a & 1) == 0) {
      a = a >> 1
      cnt += 1
    }
    cnt
  }

  def count(x: Int): Int = {
    var a = x
    var cnt = 0
    while (a > 0) {
      if ((a & 1) == 1) cnt += 1
      a = a >> 1
    }
    cnt
  }

  def hasEdge(a: Int, b: Int): Boolean = {
    edges.contains((a + 1, b + 1)) || edges.contains((b + 1, a + 1))
  }

  for {
    mask <- (1 until (1 << n))
    i <- 0 until n
  } yield {
    val xored = mask ^ (1 << i)
    if (count(mask) == 1 && bit(mask, i)) dp(mask)(i) = 1
    else if (count(mask) > 1 && first(mask) != i && bit(mask, i)) {
      (0 until n).foreach { j =>
        if (hasEdge(i, j)) dp(mask)(i) += dp(xored)(j)
      }
    } else {
      dp(mask)(i) = 0
    }
  }

  val res = for {
    mask <- (1 until (1 << n))
    i <- 0 until n
  } yield {
      if (hasEdge(first(mask), i) && count(mask) >= 3) dp(mask)(i)
      else 0
    }

  val ans = res.sum / 2

  println(ans)

}

//package me.jetblack.tspdp

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object MyDpCycles1 extends App {

  val s = new Scanner(System.in)

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

  val dp = Array.ofDim[Int](1 << n, n)

  val edges = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer.empty[Int])

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

  //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))

  (0 until m).map { _ =>
    val a = s.nextInt() - 1
    val b = s.nextInt() - 1
    edges(a) += b
    edges(b) += a
    ee(a)(b) = 1
    ee(b)(a) = 1
  }

  def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0

  def first(x: Int): Int = {
    var a = x
    var cnt = 0
    while ((a & 1) == 0) {
      a = a >> 1
      cnt += 1
    }
    cnt
  }

  def count(x: Int): Int = {
    var a = x
    var cnt = 0
    while (a > 0) {
      if ((a & 1) == 1) cnt += 1
      a = a >> 1
    }
    cnt
  }

  def cnt1(x: Int): Boolean = ((x & (x - 1)) == 0 && (x != 0))

  def hasEdge(a: Int, b: Int): Boolean = {
    ee(b)(a) == 1
  }

  var acc = 0L

  for {
    mask <- (1 until (1 << n))
    i <- 0 until n
  } yield {
    val xored = mask ^ (1 << i)
    val x = mask
    if (bit(mask, i) && ((x & (x - 1)) == 0 && (x != 0))) dp(mask)(i) = 1
    else if (bit(mask, i) && !cnt1(mask) && first(mask) != i) {
      edges(i).foreach { j =>
          dp(mask)(i) += dp(xored)(j)
          /*if (hasEdge(first(mask), i) && count(mask) >= 3)
            acc += dp(xored)(j)*/
      }
    } else {
      dp(mask)(i) = 0
    }
  }

  println(acc / 2)

}

//package me.jetblack.tspdp

//package me.jetblack.tspdp

import java.util.Scanner

object MyDpCycles1 extends App {

  val s = new Scanner(System.in)

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

  val dp = Array.ofDim[Long](1 << n, n)

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

  //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))

  (0 until m).map { _ =>
    val a = s.nextInt()
    val b = s.nextInt()
    edges(a - 1)(b - 1) = 1
    edges(b - 1)(a - 1) = 1
  }

  def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0

  def first(x: Int): Int = {
    var a = x
    var cnt = 0
    while ((a & 1) == 0) {
      a = a >> 1
      cnt += 1
    }
    cnt
  }

  def count(x: Int): Int = {
    var a = x
    var cnt = 0
    while (a > 0) {
      if ((a & 1) == 1) cnt += 1
      a = a >> 1
    }
    cnt
  }

  def hasEdge(a: Int, b: Int): Boolean = {
    false
  }

  var acc = 0L

  for {
    mask <- (1 until (1 << n))
    i <- 0 until n
  } yield {
    val xored = mask ^ (1 << i)
    if (count(mask) == 1 && bit(mask, i)) dp(mask)(i) = 1
    else if (bit(mask, i) && first(mask) != i && count(mask) > 1) {
      (0 until n).foreach { j =>
        if (hasEdge(i, j)) {
          dp(mask)(i) += dp(xored)(j)
          if (hasEdge(first(mask), i) && count(mask) >= 3)
            acc += dp(xored)(j)
          else
            0
        }
      }
    } else {
      dp(mask)(i) = 0
    }
  }

  println(acc / 2)

}

import java.util.Scanner

object MyDpCycles extends App {

  val n = 4
  val m = 6

  val s = new Scanner(System.in)

  val dp = Array.ofDim[Int](1 << n, n)

  //val edges = List((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))

  val edges = (0 until m + 1).map(_ => (s.nextInt(), s.nextInt())).drop(1)

  def bit(x: Int, pos: Int): Boolean = ((1 << pos) & x) > 0

  def first(x: Int): Int = {
    var a = x
    var cnt = 0
    while ((a & 1) == 0) {
      a = a >> 1
      cnt += 1
    }
    cnt
  }

  def count(x: Int): Int = {
    var a = x
    var cnt = 0
    while (a > 0) {
      if ((a & 1) == 1) cnt += 1
      a = a >> 1
    }
    cnt
  }

  def hasEdge(a: Int, b: Int): Boolean = {
    edges.contains((a + 1, b + 1)) || edges.contains((b + 1, a + 1))
  }

  for {
    mask <- (1 until (1 << n))
    i <- 0 until n
  } yield {
    val xored = mask ^ (1 << i)
    if (count(mask) == 1 && bit(mask, i)) dp(mask)(i) = 1
    else if (count(mask) > 1 && first(mask) != i && bit(mask, i)) {
      (0 until n).foreach { j =>
        if (hasEdge(i, j)) dp(mask)(i) += dp(xored)(j)
      }
    } else {
      dp(mask)(i) = 0
    }
  }

  val res = for {
    mask <- (1 until (1 << n) - 1)
    i <- 0 until n
  } yield {
      if (hasEdge(first(mask), i) && count(mask) >= 2) dp(mask)(i)
      else 0
    }

  val ans = res.sum / 2

  println(ans)

}


Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.

The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.

If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example.

NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique".

import scala.collection.mutable.Queue

object B extends App {

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

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

  def isEmpty(i: Int, j: Int) = i >= 0 && i < n && j >= 0 && j < m && ss(i)(j) == '.'

  def singleEmptyNeighbour(i: Int, j: Int) = {
    if (isEmpty(i + 1, j) && !isEmpty(i - 1, j) && !isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 1
    else if (!isEmpty(i + 1, j) && isEmpty(i - 1, j) && !isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 2
    else if (!isEmpty(i + 1, j) && !isEmpty(i - 1, j) && isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 3
    else if (!isEmpty(i + 1, j) && !isEmpty(i - 1, j) && !isEmpty(i, j - 1) && isEmpty(i, j + 1)) 4
    else 0
  }

  val q = Queue.empty[(Int, Int)]

  def process(i: Int, j: Int): Unit = {
    if (isEmpty(i, j)) {
      singleEmptyNeighbour(i, j) match {
        case 1 =>
          ss(i)(j) = '^'
          ss(i + 1)(j) = 'v'
          q += ((i + 1, j - 1))
          q += ((i + 1, j + 1))
          q += ((i + 2, j))
        case 2 =>
          ss(i)(j) = 'v'
          ss(i - 1)(j) = '^'
          q += ((i - 1, j - 1))
          q += ((i - 1, j + 1))
          q += ((i - 2, j))
        case 3 =>
          ss(i)(j) = '>'
          ss(i)(j - 1) = '<'
          q += ((i - 1, j - 1))
          q += ((i + 1, j - 1))
          q += ((i, j - 2))
        case 4 =>
          ss(i)(j) = '<'
          ss(i)(j + 1) = '>'
          q += ((i - 1, j + 1))
          q += ((i + 1, j + 1))
          q += ((i, j + 2))
        case 0 =>
      }
    }
  }

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

  for (i <- 0 until n; j <- 0 until m) {
    process(i, j)
    while (q.nonEmpty) {
      val (i, j) = q.dequeue()
      process(i, j)
    }
  }

  if (ss.exists(_.exists(_ == '.'))) println("Not unique")
  else ss.foreach(s => println(s.mkString))

  Console.flush
}

import scala.collection.mutable.Queue

object B extends App {

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

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

  def isEmpty(i: Int, j: Int) = i >= 0 && i < n && j >= 0 && j < m && ss(i)(j) == '.'

  def singleEmptyNeighbour(i: Int, j: Int) = {
    if (isEmpty(i + 1, j) && !isEmpty(i - 1, j) && !isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 1
    else if (!isEmpty(i + 1, j) && isEmpty(i - 1, j) && !isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 2
    else if (!isEmpty(i + 1, j) && !isEmpty(i - 1, j) && isEmpty(i, j - 1) && !isEmpty(i, j + 1)) 3
    else if (!isEmpty(i + 1, j) && !isEmpty(i - 1, j) && !isEmpty(i, j - 1) && isEmpty(i, j + 1)) 4
    else 0
  }

  val q = new java.util.ArrayDeque[(Int, Int)]()

  def process(i: Int, j: Int): Unit = {
    if (isEmpty(i, j)) {
      singleEmptyNeighbour(i, j) match {
        case 1 =>
          ss(i)(j) = '^'
          ss(i + 1)(j) = 'v'
          q.add((i + 1, j - 1))
          q.add((i + 1, j + 1))
          q.add((i + 2, j))
        case 2 =>
          ss(i)(j) = 'v'
          ss(i - 1)(j) = '^'
          q.add((i - 1, j - 1))
          q.add((i - 1, j + 1))
          q.add((i - 2, j))
        case 3 =>
          ss(i)(j) = '>'
          ss(i)(j - 1) = '<'
          q.add((i - 1, j - 1))
          q.add((i + 1, j - 1))
          q.add((i, j - 2))
        case 4 =>
          ss(i)(j) = '<'
          ss(i)(j + 1) = '>'
          q.add((i - 1, j + 1))
          q.add((i + 1, j + 1))
          q.add((i, j + 2))
        case 0 =>
      }
    }
  }

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

  for (i <- 0 until n; j <- 0 until m) {
    process(i, j)
    while (!q.isEmpty) {
      val (i, j) = q.poll()
      process(i, j)
    }
  }

  if (ss.exists(_.exists(_ == '.'))) println("Not unique")
  else ss.foreach(s => println(s.mkString))

  Console.flush
}


You are given a sequence $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ non-zero integers (i.e. $$$a_i \ne 0$$$). You have to calculate two following values:  the number of pairs of indices $$$(l, r)$$$ $$$(l \le r)$$$ such that $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ is negative;  the number of pairs of indices $$$(l, r)$$$ $$$(l \le r)$$$ such that $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ is positive;

The first line contains one integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^{5})$$$ — the number of elements in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(-10^{9} \le a_i \le 10^{9}; a_i \neq 0)$$$ — the elements of the sequence.

Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.

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

object Main extends App {
  import scala.io.StdIn._
  val n = readInt()
  val numbers = readLine.trim.split(' ').map(_.toInt)
  var positive = 0L
  var negative = 0L
  var prevNegative = -1
  var oddNegSection = 0
  var evenNegSection = 0
  for (i ← numbers) {
    if (i > 0){
      evenNegSection += 1
    }else {
      val temp = evenNegSection + 1
      evenNegSection = oddNegSection
      oddNegSection = temp
    }
    positive += evenNegSection
    negative += oddNegSection
  }
  println(s"$negative $positive")
}


Vasya is reading a e-book. The file of the book consists of $$$n$$$ pages, numbered from $$$1$$$ to $$$n$$$. The screen is currently displaying the contents of page $$$x$$$, and Vasya wants to read the page $$$y$$$. There are two buttons on the book which allow Vasya to scroll $$$d$$$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $$$10$$$ pages, and $$$d = 3$$$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. Each testcase is denoted by a line containing four integers $$$n$$$, $$$x$$$, $$$y$$$, $$$d$$$ ($$$1\le n, d \le 10^9$$$, $$$1 \le x, y \le n$$$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.

Print one line for each test. If Vasya can move from page $$$x$$$ to page $$$y$$$, print the minimum number of times he needs to press a button to do it. Otherwise print $$$-1$$$.

NoteIn the first test case the optimal sequence is: $$$4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$$$.In the second test case it is possible to get to pages $$$1$$$ and $$$5$$$.In the third test case the optimal sequence is: $$$4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$$$.

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 = {
    rep(ni()) { _ =>
      val n, x, y = ni() - 1
      val d = ni()
      val one = if (y % d == 0) x / d + (if (x % d > 0) 1 else 0) + y / d else Integer.MAX_VALUE
      val last = if ((n - y) % d == 0) (n - x) / d + (if ((n - x) % d > 0) 1 else 0) + (n - y) / d else Integer.MAX_VALUE
      val direct = if (abs(y - x) % d == 0) abs(y - x) / d else Integer.MAX_VALUE
      val ans = min(one, min(last, direct))
      out.println(if (ans == Integer.MAX_VALUE) -1 else 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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object EDU_55_A {
  def solve(input: Vector[Int]): Int = {
    val Seq(n,x,y,d) = input
    // Page y is reachable iff:
        //1 x+kd = y where k can be + or -, and |k| is answer ||
        //2 1+kd = y where k is + ||
        //3 n-kd = y "
    // 1
    if ((y - x)%d == 0)
      math.abs((y - x) / d)
    //2
    else {
      val via1 = if ((y - 1) % d == 0)
      // presses to get back to start
        Some(intCeil(x - 1, d) +
          // presses to get up to place
          intCeil(y - 1, d)) else None
      val viaN = if ((n - y) % d == 0)
        Some(intCeil(n - x, d) +
          intCeil(n - y, d)) else None
      Seq(via1, viaN).flatten match {
        case Seq() => -1
        case Seq(a) => a
        case Seq(a,b) => a min b
      }
    }

  }

  // unintuitive but robust way of getting ceil(a/b) for ints
  def intCeil(a: Int, b: Int) = (a + b - 1) / b

  def main(args: Array[String]) = {
    val io = new IO(System.in)
    val lines = io.int()
    io.nextLine
    1 to lines foreach { _ =>
      println(solve(io.intSeq()))
    }
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def double() = sc.nextDouble()
    }
}

object EDU_55_A {
  def solve(input: Vector[Int]): Int = {
    val Seq(n,x,y,d) = input
    // Page y is reachable iff:
        //1 x+kd = y where k can be + or -, and |k| is answer ||
        //2 1+kd = y where k is + ||
        //3 n-kd = y " ||
    // 1
    if ((y - x)%d == 0)
      math.abs((y - x) / d)
    //2
    else if ((y - 1) % d == 0)
      // presses to get back to start
      intCeil(x-1, d) +
      // presses to get up to place
        (y - 1) / d
    else if ((n-y) % d == 0)
      intCeil(n - x, d) +
        (n-y)/d
    else -1
  }

  // unintuitive but robust way of getting ceil(a/b) for ints
  def intCeil(a: Int, b: Int) = (a + b - 1) / b

  def main(args: Array[String]) = {
    val io = new IO(System.in)
    val lines = io.int()
    io.nextLine
    1 to lines foreach { _ =>
      println(solve(io.intSeq()))
    }
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def double() = sc.nextDouble()
    }
}

object EDU_55_A {
  def solve(input: Vector[Int]): Int = {
    val Seq(n,x,y,d) = input
    // Page y is reachable iff:
        //1 x+kd = y where k can be + or -, and |k| is answer ||
        //2 1+kd = y where k is + ||
        //3 n-kd = y "
    // 1
    if ((y - x)%d == 0)
      math.abs((y - x) / d)
    //2
    else {
      val via1 = if ((y - 1) % d == 0)
      // presses to get back to start
        Some(intCeil(x - 1, d) +
          // presses to get up to place
          intCeil(y - 1, d)) else None
      val viaN = if ((n - y) % d == 0)
        Some(intCeil(n - x, d) +
          intCeil(n - y, d)) else None
      Seq(via1, viaN).flatten match {
        case Seq() => -1
        case Seq(a) => a
        case Seq(a,b) => a max b
      }
    }

  }

  // unintuitive but robust way of getting ceil(a/b) for ints
  def intCeil(a: Int, b: Int) = (a + b - 1) / b

  def main(args: Array[String]) = {
    val io = new IO(System.in)
    val lines = io.int()
    io.nextLine
    1 to lines foreach { _ =>
      println(solve(io.intSeq()))
    }
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def double() = sc.nextDouble()
    }
}

object EDU_55_A {
  def solve(input: Vector[Int]): Int = {
    val Seq(n,x,y,d) = input
    // Page y is reachable iff:
        //1 x+kd = y where k can be + or -, and |k| is answer ||
        //2 1+kd = y where k is + ||
        //3 n-kd = y "
    // 1
    if ((y - x)%d == 0)
      math.abs((y - x) / d)
    //2
    else if ((y - 1) % d == 0)
      // presses to get back to start
      intCeil(x-1, d) +
      // presses to get up to place
       intCeil(y-1,d)
    else if ((n-y) % d == 0)
      intCeil(n - x, d) +
        intCeil(n-y,d)
    else -1
  }

  // unintuitive but robust way of getting ceil(a/b) for ints
  def intCeil(a: Int, b: Int) = (a + b - 1) / b

  def main(args: Array[String]) = {
    val io = new IO(System.in)
    val lines = io.int()
    io.nextLine
    1 to lines foreach { _ =>
      println(solve(io.intSeq()))
    }
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def double() = sc.nextDouble()
    }
}

object EDU_55_A {
  def solve(input: Vector[Int]): Int = {
    val Seq(n,x,y,d) = input
    // Page y is reachable iff:
        //1 x+kd = y where k can be + or -, and |k| is answer ||
        //2 1+kd = y where k is + ||
        //3 n-kd = y " ||
    // 1
    if ((y - x)%d == 0)
      math.abs((y - x) / d)
    //2
    else if ((y - 1) % d == 0)
      // presses to get back to start
      math.ceil((x - 1)/d.toDouble).toInt +
      // presses to get up to place
        (y - 1) / d
    else if ((n-y) % d == 0)
      math.ceil((n - x)/d.toDouble).toInt +
        (n-y)/d
    else -1
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in)
    val lines = io.int()
    io.nextLine
    1 to lines foreach { _ =>
      println(solve(io.intSeq()))
    }

  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def double() = sc.nextDouble()
    }
}


"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?

First line consists of a single integer n (1 ≤ n ≤ 105) — the number of stewards with Jon Snow. Second line consists of n space separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) representing the values assigned to the stewards.

Output a single integer representing the number of stewards which Jon will feed.

NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.

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

object _768A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val stewards = read[Vector[Int]].sorted
    val minLeft = stewards.scanLeft(Int.MaxValue)(_ min _)
    val maxRight = stewards.scanRight(Int.MinValue)(_ max _)

    val ans = stewards.indices count {i =>
      minLeft(i) < stewards(i) && stewards(i) < maxRight(i)
    }

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

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

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

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

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

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

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}