You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.Determine the least number of replaces to make the string s RBS.

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.

import util.control.Breaks._
import scala.collection.mutable.Stack

object brackets {
  def main(args: Array[String]) {
    var ans = 0
    val left  = "<{[("
    val right = ">}])"

    val s = scala.io.StdIn.readLine
    var stack = new Stack[Char]
    breakable {
      s.foreach { c =>
        if (left.contains(c)) {
          stack.push(c)
        } else if (right.contains(c)) {
          val pos = right.indexOf(c)
          if (stack.isEmpty) {
            ans = -1
            break
          }
          var tmp = stack.pop
          if (tmp != left(pos)) ans+=1
        }
        //stack.push(_)
      }
    }
    if (ans == -1 || !stack.isEmpty) println("Impossible")
    else println(ans)
  }
}

import java.util.Scanner
import scala.annotation.tailrec

object Main {
  val L = "<{[("
  val R = ">}])"
  def main(args: Array[String]) {
    val scan = new Scanner(System.in)
    val inStr = scan.nextLine()
    scan.close()

    val res = Process(inStr,0,Nil,0,0)
    if(res<0){
      print("Impossible")
    }else{
      print(res)
    }
  }

  @tailrec
  def Process(str: String, i: Int, p: List[Int], f:Int,res: Int): Int = {
    if (i >= str.length || res < 0) {
      if(f==0) res else -1
    } else {
      if(L.contains(str(i))){
        Process(str,i+1,L.indexOf(str(i))::p,f+1,res+1)
      }else{
        if(p.isEmpty){
          -1
        }else{
          if(p.head == R.indexOf(str(i))){
            Process(str,i+1,p.drop(1),f-1,res-1)
          }else{
            Process(str,i+1,p.drop(1),f-1,res)
          }
        }
      }
    }
  }
}

import util.control.Breaks._
import scala.collection.mutable.Stack

object brackets {
  def main(args: Array[String]) {
    var ans = 0
    val left  = "<{[("
    val right = ">}])"

    val s = scala.io.StdIn.readLine
    var stack = new Stack[Char]
    breakable {
      s.foreach { c =>
        if (left.contains(c)) {
          stack.push(c)
        } else if (right.contains(c)) {
          val pos = right.indexOf(c)
          if (stack.isEmpty) {
            ans = -1
            break
          }
          var tmp = stack.pop
          if (tmp != left(pos)) ans+=1
        }
        //stack.push(_)
      }
    }
    if (ans == -1) println("Impossible")
    else println(ans)
  }
}

import java.util.Scanner
import scala.annotation.tailrec

object Main {
  val L = "<{[("
  val R = ">}])"
  def main(args: Array[String]) {
    val scan = new Scanner(System.in)
    val inStr = scan.nextLine()
    scan.close()

    val res = Process(inStr,0,Nil,0)
    if(res<0){
      print("Impossible")
    }else{
      print(res)
    }
  }

  @tailrec
  def Process(str: String, i: Int, p: List[Int], res: Int): Int = {
    if (i >= str.length || res < 0) {
      res
    } else {
      if(L.contains(str(i))){
        Process(str,i+1,L.indexOf(str(i))::p,res+1)
      }else{
        if(p.isEmpty){
          -1
        }else{
          if(p.head == R.indexOf(str(i))){
            Process(str,i+1,p.drop(1),res-1)
          }else{
            Process(str,i+1,p.drop(1),res)
          }
        }
      }
    }
  }
}


A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.

The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). All the numbers in the lines are separated by single spaces.

On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.

NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println(data.sorted.foldLeft(Set.empty[Int]) {
    case (set, a) if a % k != 0 => set + a
    case (set, a) if !set.contains(a / k) => set + a
    case (set, a) => set
  }.size)
}

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

import scala.collection.mutable
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 C168A(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 C168A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val k = ni()

    val a = na(n).toIndexedSeq.sorted
    val hm = new mutable.HashMap[Int, Boolean]()
    var count = 0
    REP(n) { i =>
      if(a(i) % k == 0) {
        val v = a(i) / k
        if(!hm.contains(v)) {
          count+=1
          hm(a(i)) = true
        }
      } else {
        count+=1
        hm(a(i)) = true
      }
    }
    out.println(count)
  }
}

import collection.mutable.Queue
import java.util.Scanner
import java.io._
import scala.io.Source

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val a=readLine.split(" ").map(_.toLong).sorted
    val set1=a.toSet
    val set2=collection.mutable.Set[Long]()

    a.foreach(i=>{
        if(!set2.contains(i)){
            if(i!=i*k && set1.contains(i*k)) set2+=i*k
        }
    })

    println(set1.size-set2.size)

}

import java.util.Scanner

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

object Main {
  val scanner = new Scanner(System.in)
  def main(args: Array[String]): Unit = {
    val Array(n, k) = scanner.nextLine().split(" ").map(_.toInt)
    var v: Vector[Int] = Vector[Int]()
    for(i <- 1 to n) {
      val temp = scanner.nextInt()
      v = v :+ temp
    }
    v = v.sorted
    val s = mutable.HashSet[Int]()
    v.foreach(p => {
      if ((p%k!=0) || !s.contains(p/k)) {
        s.add(p)
      }
    })
    println(s.size)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println(data.sorted.foldLeft(Set.empty[Int]) {
    case (set, a) if a % k == 0 && !set.contains(a / k) => set + a
    case (set, a)  => set
  }.size)
}

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val k = ni().toLong

    a = na(n).toIndexedSeq.sorted
    var mx = -1
    REP(n) { i =>
      var from = i
      var count = 1
      var target = a(from) * k
      while (from < n) {
        val id = bs(from, n-1, target)
        count += (id - from)
        from = id + 1
        target = a(id) * k
      }
      if(mx < count) mx = count
    }
    out.println(mx)
  }

  var a: IndexedSeq[Int] = _

  def bs(from: Int, to: Int, v: Long): Int = {
    var l = from
    var r = to

    while (r - l > 1) {
      val m = l + (r - l) / 2
      if(a(m) >= v) r = m-1
      else l = m
    }
    if(a(r) >= v) l
    else r
  }
}

import collection.mutable.Queue
import java.util.Scanner
import java.io._
import scala.io.Source

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val a=readLine.split(" ").map(_.toLong).sorted
    val set1=a.toSet
    val set2=collection.mutable.Set[Long]()

    a.foreach(i=>{
        if(!set2.contains(i)){
            if(set1.contains(i*k)) set2+=i*k
        }
    })

    println(set1.size-set2.size)

}

import collection.mutable.Queue
import java.util.Scanner
import java.io._
import scala.io.Source

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val a=readLine.split(" ").map(_.toInt).sorted
    val set1=a.toSet
    val set2=collection.mutable.Set[Int]()

    a.foreach(i=>{
        if(!set2.contains(i)){
            if(set1.contains(i*k)) set2+=i*k
        }
    })

    println(set1.size-set2.size)

}

import java.util.Scanner

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

object Main {
  val scanner = new Scanner(System.in)
  def main(args: Array[String]): Unit = {
    val Array(n, k) = scanner.nextLine().split(" ").map(_.toInt)
    var v: Vector[Int] = Vector[Int]()
    for(i <- 1 to n) {
      val temp = scanner.nextInt()
      v = v :+ temp
    }
    v = v.sorted
    val s = mutable.HashSet[Int]()
    v.foreach(p => {
      if (!s.contains(p/k)) {
        s.add(p)
      }
    })
    println(s.size)
  }
}


There are $$$n$$$ cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from $$$1$$$ to $$$n$$$.Two fairs are currently taking place in Berland — they are held in two different cities $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le n$$$; $$$a \ne b$$$).Find the number of pairs of cities $$$x$$$ and $$$y$$$ ($$$x \ne a, x \ne b, y \ne a, y \ne b$$$) such that if you go from $$$x$$$ to $$$y$$$ you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities $$$x,y$$$ such that any path from $$$x$$$ to $$$y$$$ goes through $$$a$$$ and $$$b$$$ (in any order).Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs $$$(x,y)$$$ and $$$(y,x)$$$ must be taken into account only once.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 4\cdot10^4$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are specified. The first line of each test case contains four integers $$$n$$$, $$$m$$$, $$$a$$$ and $$$b$$$ ($$$4 \le n \le 2\cdot10^5$$$, $$$n - 1 \le m \le 5\cdot10^5$$$, $$$1 \le a,b \le n$$$, $$$a \ne b$$$) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively. The following $$$m$$$ lines contain descriptions of roads between cities. Each of road description contains a pair of integers $$$u_i, v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) — numbers of cities connected by the road. Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities. The sum of the values of $$$n$$$ for all sets of input data in the test does not exceed $$$2\cdot10^5$$$. The sum of the values of $$$m$$$ for all sets of input data in the test does not exceed $$$5\cdot10^5$$$.

Print $$$t$$$ integers — the answers to the given test cases in the order they are written in the input.

import scala.collection.mutable

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

  val t = nextInt
  for (_ <- 1 to t) {
    val n, m, a, b = nextInt
    val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)
    for (_ <- 1 to m) {
      val u, v = nextInt - 1
      adjBuilders(u) += v
      adjBuilders(v) += u
    }
    val adjs = adjBuilders.map(_.result())

    def bfs(u0: Int, block: Int): Long = {
      val que = new java.util.ArrayDeque[Int]
      val visited = mutable.BitSet(n)
      visited(u0) = true
      que.add(u0)
      while (!que.isEmpty) {
        val u = que.pollFirst()
        if (u != block) {
          var i = 0
          while (i < adjs(u).length) {
            val v = adjs(u)(i)
            if (!visited(v)) {
              visited += v
              que.add(v)
            }
            i += 1
          }
        }
      }
      var i = 0
      var count = 0L
      while (i < n) {
        if (!visited(i)) count += 1
        i += 1
      }
      count
    }

    val c1 = bfs(a - 1, b - 1)
    val c2 = bfs(b - 1, a - 1)
    out.println(c1 * c2)
  }

  out.flush()

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


Mihai has just learned about the MEX concept and since he liked it so much, he decided to use it right away.Given an array $$$a$$$ of $$$n$$$ non-negative integers, Mihai wants to create a new array $$$b$$$ that is formed in the following way:While $$$a$$$ is not empty:   Choose an integer $$$k$$$ ($$$1 \leq k \leq |a|$$$).  Append the MEX of the first $$$k$$$ numbers of the array $$$a$$$ to the end of array $$$b$$$ and erase them from the array $$$a$$$, shifting the positions of the remaining numbers in $$$a$$$. But, since Mihai loves big arrays as much as the MEX concept, he wants the new array $$$b$$$ to be the lexicographically maximum. So, Mihai asks you to tell him what the maximum array $$$b$$$ that can be created by constructing the array optimally is.An array $$$x$$$ is lexicographically greater than an array $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ $$$x_i > y_i$$$ or if $$$|x| > |y|$$$ and $$$y$$$ is a prefix of $$$x$$$ (where $$$|x|$$$ denotes the size of the array $$$x$$$).The MEX of a set of non-negative integers is the minimal non-negative integer such that it is not in the set. For example, MEX({$$${1, 2, 3}$$$}) $$$= 0$$$ and MEX({$$${0, 1, 2, 4, 5}$$$}) $$$= 3$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of elements in the array $$$a$$$. The second line of each test case contains $$$n$$$ non-negative integers $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i \leq n$$$), where $$$a_i$$$ is the $$$i$$$-th integer from the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print $$$m$$$ — the length of the maximum array $$$b$$$ Mihai can create, followed by $$$m$$$ integers denoting the elements of the array $$$b$$$.

NoteIn the first test case, the lexicographically maximum array $$$b$$$ is obtained by selecting $$$k=5$$$, resulting in the $$$MEX$$$ of the whole array $$$a$$$. It is lexicographically maximum because an array starting with a smaller number than $$$4$$$ is lexicographically smaller, and choosing a $$$k<5$$$ would result in an array starting with a number smaller than $$$4$$$.In the second test case, there are two ways to obtain the maximum array: first selecting $$$k=6$$$, then $$$k=2$$$, or first selecting $$$k=7$$$ and then $$$k=1$$$.

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var a: Int, var b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n+2)
        val cnt = new Array[Int](n+2)
        var ans = Vector[Int]()
        for (i <- 1 to n) {
            arr(i) = readInt()
            cnt(arr(i)) += 1
        }
        var k = 0
        while (cnt(k) != 0) {
            k += 1
        }
        val mark = new Array[Boolean](n+2)
        var tmp = 0
        var po = 1
        var newk = k

        while (po <= n && k > 0) {
            tmp = -1
            while (tmp < k) {
                if (!mark(arr(po)) && arr(po) <= k) {
                    mark(arr(po)) = true
                    if (tmp == -1)
                        tmp = 1
                    else
                        tmp += 1
                }
                cnt(arr(po)) -= 1
                if (cnt(arr(po)) == 0) {
                    newk = min(newk, arr(po))
                }
                po += 1
            }
            for (i <- 0 to newk) {
                mark(i) = false
            }
            ans :+= k
            k = newk
        }
        while (po <= n) {
            ans :+= 0
            po += 1
        }
        writer.println(ans.length)
        for (m <- ans) {
            writer.print(m + " ")
        }
        writer.println()

        def check(kk: Long, fi: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long, fi:Long): Long = {
            if (en - st <= 1L) {
                if (check(st, fi))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid, fi))
                return bs(st, mid, fi)
            else
                return bs(mid, en, fi)
        }
    }
    writer.flush()
}


As you know, Vova has recently become a new shaman in the city of Ultima Thule. So, he has received the shaman knowledge about the correct bracket sequences. The shamans of Ultima Thule have been using lots of different types of brackets since prehistoric times. A bracket type is a positive integer. The shamans define a correct bracket sequence as follows:  An empty sequence is a correct bracket sequence.  If {a1, a2, ..., al} and {b1, b2, ..., bk} are correct bracket sequences, then sequence {a1, a2, ..., al, b1, b2, ..., bk} (their concatenation) also is a correct bracket sequence.  If {a1, a2, ..., al} — is a correct bracket sequence, then sequence  also is a correct bracket sequence, where v (v > 0) is an integer. For example, sequences {1, 1,  - 1, 2,  - 2,  - 1} and {3,  - 3} are correct bracket sequences, and {2,  - 3} is not.Moreover, after Vova became a shaman, he learned the most important correct bracket sequence {x1, x2, ..., xn}, consisting of n integers. As sequence x is the most important, Vova decided to encrypt it just in case.Encrypting consists of two sequences. The first sequence {p1, p2, ..., pn} contains types of brackets, that is, pi = |xi| (1 ≤ i ≤ n). The second sequence {q1, q2, ..., qt} contains t integers — some positions (possibly, not all of them), which had negative numbers in sequence {x1, x2, ..., xn}.Unfortunately, Vova forgot the main sequence. But he was lucky enough to keep the encryption: sequences {p1, p2, ..., pn} and {q1, q2, ..., qt}. Help Vova restore sequence x by the encryption. If there are multiple sequences that correspond to the encryption, restore any of them. If there are no such sequences, you should tell so.

The first line of the input contains integer n (1 ≤ n ≤ 106). The second line contains n integers: p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains integer t (0 ≤ t ≤ n), followed by t distinct integers q1, q2, ..., qt (1 ≤ qi ≤ n). The numbers in each line are separated by spaces.

Print a single string "NO" (without the quotes) if Vova is mistaken and a suitable sequence {x1, x2, ..., xn} doesn't exist. Otherwise, in the first line print "YES" (without the quotes) and in the second line print n integers x1, x2, ..., xn (|xi| = pi; xqj < 0). If there are multiple sequences that correspond to the encrypting, you are allowed to print any of them.

import java.io.ByteArrayInputStream

import scala.collection.mutable

object Main {

  var dddd = false

  def ptime() = if (dddd) println(System.currentTimeMillis())
  def delog(a: String) = if (dddd) println(a)

  def main(args: Array[String]) = {
    /** setup **/
    var debug: Object => Unit = null
    if (!args.isEmpty && args.head == "test") {
      dddd = true
      debug = println
      val TEST =
        """2
          |1 1
          |0
        """.stripMargin
      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }
    val input = scala.io.Source.stdin.getLines()

    /** parse **/ ptime()

    input.next()
    val ps = input.next().split(" ").map(_.toInt)
    val qs = input.next().split(" ").drop(1).map(_.toInt - 1)
    //    val ps = (0 until 10000).map(i => 1)
    //    val qs = Set.empty[Int]

    /** algorithm **/ ptime()

    /// copied... still don't know why greedy works

    qs.foreach(q => {
      val p = ps(q)
      ps(q) = -p
    })

    var i = ps.size - 1
    var stack = List.empty[Int]

    while (i >= 0) {
      val p = ps(i)
      if (p < 0) {
        stack = p +: stack
        i = i - 1
      } else {
        val valid = stack.nonEmpty && stack.head == -p
        if (valid) {
          stack = stack.tail
          i = i - 1
        } else {
          stack = -p +: stack
          ps(i) = -p
          i = i - 1
        }
      }
    }

    val sol = if (stack.isEmpty) {
      Some(ps)
    } else {
      None
    }

    //    val sol = found.map(list => {
    //      val m = list.toSet
    //      ps.zipWithIndex.map(pair => if (m(pair._2)) -pair._1 else pair._1)
    //    })

    //// non-recursive one... but didn't not work, I need to know why the greedy one worked
    //    var i = 0
    //    var stack: Seq[Int] = List.empty
    //    var comm: Seq[Int] = List.empty
    //    var alternatives: Seq[() => Unit] = List.empty
    //
    //    var found: Option[Seq[Int]] = None
    //    var finished = false
    //
    //
    //    def goBack() = {
    //      if (alternatives.isEmpty) {
    //        finished = true
    //      } else {
    //        val head = alternatives.head
    //        alternatives = alternatives.tail
    //        head()
    //      }
    //    }
    //    while (!finished) {
    //      while (i < ps.size) {
    //        if (stack.size > ps.size - i) {
    //          goBack()
    //        } else {
    //          val p = ps(i)
    //          val q = qs(i)
    //          if (q) {
    //            if (stack.nonEmpty && p == stack.head) {
    //              comm = i +: comm
    //              i = i + 1
    //              stack = stack.tail
    //            } else {
    //              goBack()
    //            }
    //          } else {
    //            val valid = stack.nonEmpty && p == stack.head
    //            if (valid) {
    //              val cc = comm
    //              val ss = p +: stack
    //              val ii = i + 1
    //              alternatives = (() => {
    //                comm = cc
    //                stack = ss
    //                i = ii
    //              }) +: alternatives
    //              comm = i +: comm
    //              i = i + 1
    //              stack = stack.tail
    ////              val cc = i +: comm
    ////              val ii = i + 1
    ////              val ss = stack.tail
    ////              alternatives = (() => {
    ////                i = ii
    ////                stack = ss
    ////                comm = cc
    ////              }) +: alternatives
    //            }
    //            i = i + 1
    //            stack = p +: stack
    //          }
    //        }
    //      }
    //      if (stack.isEmpty) {
    //        found = Some(comm)
    //        finished = true
    //      } else {
    //        goBack()
    //      }
    //    }
    //
    //

    //// recursive one, did not work

    //    def rec(i: Int, stack: Seq[Int], comm: Seq[Int]): Option[Seq[Int]] = {
    //      if (i == ps.length) {
    //        if (stack.isEmpty) Some(comm)
    //        else None
    //      } else {
    //        val p = ps(i)
    //        val q = qs(i)
    //        if (q) {
    //          if (stack.nonEmpty && p == stack.head) {
    //            rec(i + 1, stack.tail, i +: comm)
    //          } else {
    //            None
    //          }
    //        } else {
    //          val valid = stack.nonEmpty && p == stack.head
    //          if (valid) {
    //            val k = rec(i + 1, stack.tail, i +: comm)
    //            if (k.nonEmpty) return k
    //          }
    //          rec(i + 1, p +: stack, comm)
    //        }
    //      }
    //    }

    /** print **/ ptime()

//    if (sol.isEmpty) {
//      println("NO")
//    } else {
//      println("YES")
//      val list = sol.get
//      var i = 0
//      while (i < list.size - 1) {
//        print(list(i))
//        print(" ")
//        i += 1
//      }
//      println(list.last)
//    }
    println(sol.map(list => "YES\n" + list.mkString(" ")).getOrElse("NO"))
  }

}

import java.io.ByteArrayInputStream

import scala.collection.mutable

object Main {

  var dddd = false

  def ptime() = if (dddd) println(System.currentTimeMillis())
  def delog(a: String) = if (dddd) println(a)

  def main(args: Array[String]) = {
    /** setup **/
    var debug: Object => Unit = null
    if (!args.isEmpty && args.head == "test") {
      dddd = true
      debug = println
      val TEST =
        """4
          |1 2 2 1
          |2 3 4
        """.stripMargin
      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }
    val input = scala.io.Source.stdin.getLines()

    /** parse **/ ptime()

    input.next()
    val ps = input.next().split(" ").map(_.toInt)
    val qs = input.next().split(" ").drop(1).map(_.toInt - 1)
    //    val ps = (0 until 10000).map(i => 1)
    //    val qs = Set.empty[Int]

    /** algorithm **/ ptime()

    /// copied... still don't know why greedy works

    qs.foreach(q => {
      val p = ps(q)
      ps(q) = -p
    })

    var i = ps.size - 1
    var stack = List.empty[Int]

    while (i >= 0) {
      val p = ps(i)
      if (p < 0) {
        stack = p +: stack
        i = i - 1
      } else {
        val valid = stack.nonEmpty && stack.head == -p
        if (valid) {
          stack = stack.tail
          i = i - 1
        } else {
          stack = p +: stack
          ps(i) = -p
          i = i - 1
        }
      }
    }
    val sol = if (stack.isEmpty) {
      Some(ps)
    } else {
      None
    }

    //    val sol = found.map(list => {
    //      val m = list.toSet
    //      ps.zipWithIndex.map(pair => if (m(pair._2)) -pair._1 else pair._1)
    //    })

    //// non-recursive one... but didn't not work, I need to know why the greedy one worked
    //    var i = 0
    //    var stack: Seq[Int] = List.empty
    //    var comm: Seq[Int] = List.empty
    //    var alternatives: Seq[() => Unit] = List.empty
    //
    //    var found: Option[Seq[Int]] = None
    //    var finished = false
    //
    //
    //    def goBack() = {
    //      if (alternatives.isEmpty) {
    //        finished = true
    //      } else {
    //        val head = alternatives.head
    //        alternatives = alternatives.tail
    //        head()
    //      }
    //    }
    //    while (!finished) {
    //      while (i < ps.size) {
    //        if (stack.size > ps.size - i) {
    //          goBack()
    //        } else {
    //          val p = ps(i)
    //          val q = qs(i)
    //          if (q) {
    //            if (stack.nonEmpty && p == stack.head) {
    //              comm = i +: comm
    //              i = i + 1
    //              stack = stack.tail
    //            } else {
    //              goBack()
    //            }
    //          } else {
    //            val valid = stack.nonEmpty && p == stack.head
    //            if (valid) {
    //              val cc = comm
    //              val ss = p +: stack
    //              val ii = i + 1
    //              alternatives = (() => {
    //                comm = cc
    //                stack = ss
    //                i = ii
    //              }) +: alternatives
    //              comm = i +: comm
    //              i = i + 1
    //              stack = stack.tail
    ////              val cc = i +: comm
    ////              val ii = i + 1
    ////              val ss = stack.tail
    ////              alternatives = (() => {
    ////                i = ii
    ////                stack = ss
    ////                comm = cc
    ////              }) +: alternatives
    //            }
    //            i = i + 1
    //            stack = p +: stack
    //          }
    //        }
    //      }
    //      if (stack.isEmpty) {
    //        found = Some(comm)
    //        finished = true
    //      } else {
    //        goBack()
    //      }
    //    }
    //
    //

    //// recursive one, did not work

    //    def rec(i: Int, stack: Seq[Int], comm: Seq[Int]): Option[Seq[Int]] = {
    //      if (i == ps.length) {
    //        if (stack.isEmpty) Some(comm)
    //        else None
    //      } else {
    //        val p = ps(i)
    //        val q = qs(i)
    //        if (q) {
    //          if (stack.nonEmpty && p == stack.head) {
    //            rec(i + 1, stack.tail, i +: comm)
    //          } else {
    //            None
    //          }
    //        } else {
    //          val valid = stack.nonEmpty && p == stack.head
    //          if (valid) {
    //            val k = rec(i + 1, stack.tail, i +: comm)
    //            if (k.nonEmpty) return k
    //          }
    //          rec(i + 1, p +: stack, comm)
    //        }
    //      }
    //    }

    /** print **/ ptime()

    if (sol.isEmpty) {
      println("NO")
    } else {
      println("YES")
      val list = sol.get
      var i = 0
      while (i < list.size - 1) {
        print(list(i))
        print(" ")
        i += 1
      }
      println(list.last)
    }
    //println(sol.map(list => "YES\n" + list.mkString(" ")).getOrElse("NO"))
  }

}

import java.io.ByteArrayInputStream

import scala.collection.mutable

object Main {

  var dddd = false

  def ptime() = if (dddd) println(System.currentTimeMillis())
  def delog(a: String) = if (dddd) println(a)

  def main(args: Array[String]) = {
    /** setup **/
    var debug: Object => Unit = null
    if (!args.isEmpty && args.head == "test") {
      dddd = true
      debug = println
      val TEST =
        """4
          |1 1 1 1
          |1 3
        """.stripMargin
      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }
    val input = scala.io.Source.stdin.getLines()

    /** parse **/ ptime()

    input.next()
    val ps = input.next().split(" ").map(_.toInt)
    val qs = input.next().split(" ").drop(1).map(_.toInt - 1).toSet

    /** algorithm **/ ptime()

    def rec(i: Int, stack: Seq[Int]): Option[Seq[Int]] = {
      if (i == ps.length) {
        Some(List.empty[Int])
      } else {
        val p = ps(i)
        val q = qs(i)
        if (q) {
          if (stack.nonEmpty && p == stack.head) {
            rec(i + 1, stack.tail).map(l => i +: l)
          } else {
            None
          }
        } else {
          val valid = stack.nonEmpty && p == stack.head
          if (valid) {
            val k = rec(i + 1, stack.tail).map(l => i +: l)
            if (k.nonEmpty) return k
          }
          rec(i + 1, p +: stack)
        }
      }
    }

    val sol = rec(0, List.empty).map(list => {
      val m = list.toSet
      ps.zipWithIndex.map(pair => if (m(pair._2)) -pair._1 else pair._1)
    })

    /** print **/ ptime()

    println(sol.map(list => "YES\n" + list.mkString(" ")).getOrElse("NO"))
  }
}

import java.io.ByteArrayInputStream

import scala.collection.mutable

object Main {

  var dddd = false

  def ptime() = if (dddd) println(System.currentTimeMillis())
  def delog(a: String) = if (dddd) println(a)

  def main(args: Array[String]) = {
    /** setup **/
    var debug: Object => Unit = null
    if (!args.isEmpty && args.head == "test") {
      dddd = true
      debug = println
      val TEST =
        """4
          |1 1 1 1
          |1 3
        """.stripMargin
      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }
    val input = scala.io.Source.stdin.getLines()

    /** parse **/ ptime()

    input.next()
    val ps = input.next().split(" ").map(_.toInt)
    val qs = input.next().split(" ").drop(1).map(_.toInt - 1).toSet

    /** algorithm **/ ptime()

    def rec(i: Int, stack: Seq[Int]): Option[Seq[Int]] = {
      if (i == ps.length) {
        Some(List.empty[Int])
      } else {
        val p = ps(i)
        val q = qs(p)
        if (q) {
          if (stack.nonEmpty && p == stack.head) {
            rec(i + 1, stack.tail).map(l => i +: l)
          } else {
            None
          }
        } else {
          val valid = stack.nonEmpty && p == stack.head
          if (valid) {
            val k = rec(i + 1, stack.tail).map(l => i +: l)
            if (k.nonEmpty) return k
          }
          rec(i + 1, p +: stack)
        }
      }
    }

    val sol = rec(0, List.empty).map(list => {
      val m = list.toSet
      ps.zipWithIndex.map(pair => if (m(pair._2)) -pair._1 else pair._1)
    })

    /** print **/ ptime()

    println(sol.map(list => "YES\n" + list.mkString(" ")).getOrElse("NO"))
  }
}


Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj).

The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly.  The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array.

Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).

import scala.collection.mutable._

object Solution {
  def solve(arr: Array[Int], k: Int): Long = {
    val map = new HashMap[Int, ArrayBuffer[Int]]()
    for (i <- 0 until arr.length) {
      map.getOrElseUpdate(arr(i), new ArrayBuffer[Int]).append(i)
    }

    var minRight = Array.fill(arr.length)(arr.length)
    for ((key, offsets) <- map) {
      for (i <- 0 to offsets.length-k) {
        minRight(offsets(i)) = offsets(i+k-1)
      }
    }

    minRight = minRight.scanRight(minRight.length)(_ min _)
    minRight.map(arr.length - _.toLong).sum
  }

  def main(args: Array[String]) {
    val k = readLine().split(" ")(1).toInt
    val arr = readLine().split(" ").map(_.toInt)
    println(solve(arr, k))
  }
}

import scala.collection.mutable._

object Solution {
  def solve(arr: Array[Int], k: Int): Long = {
    val map = new HashMap[Int, ArrayBuffer[Int]]()
    for (i <- 0 until arr.length) {
      map.getOrElseUpdate(arr(i), ArrayBuffer(i)).append(i)
    }

    var minRight = Array.fill(arr.length)(arr.length)
    for ((key, offsets) <- map) {
      for (i <- 0 to offsets.length-k) {
        minRight(offsets(i)) = offsets(i+k-1)
      }
    }

    minRight = minRight.scanRight(minRight.length)(_ min _)
    minRight.map(arr.length - _.toLong).sum
  }

  def main(args: Array[String]) {
    val k = readLine().split(" ")(1).toInt
    val arr = readLine().split(" ").map(_.toInt)
    println(solve(arr, k))
  }
}

import scala.collection.mutable._

object Solution {
  def solve(arr: Array[Int], k: Int): Long = {
    val map = new HashMap[Int, ArrayBuffer[Int]]()
    for (i <- 0 until arr.length) {
      val x = arr(i)
      if (map.get(x).isEmpty) {
        map.put(x, new ArrayBuffer[Int])
      }
      map.get(x).get.append(i)
    }

    var minRight = Array.ofDim[Int](arr.length)
    for (i <- 0 until minRight.length) {
      minRight(i) = minRight.length
    }

    for ((key, value) <- map) {
      for (i <- 0 to value.length-k) {
        minRight(value(i)) = minRight(value(i)) min value(i+k-1)
      }
    }

    var ans: Long = 0;
    for (i <- 0 until minRight.length) {
      val j = minRight.length-i-1
      if (i > 0) {
        minRight(j) = minRight(j) min minRight(j+1)
      }
      ans += arr.length - minRight(i)
    }
    ans
  }

  def main(args: Array[String]) {
    val k = readLine().split(" ")(1).toInt
    val arr = readLine().split(" ").map(_.toInt)
    println(solve(arr, k))
  }
}


You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad.A substring s[l...r] (1 ≤ l ≤ r ≤ |s|) of string s  =  s1s2...s|s| (where |s| is the length of string s) is string  slsl + 1...sr.The substring s[l...r] is good, if among the letters  sl, sl + 1, ..., sr there are at most k bad ones (look at the sample's explanation to understand it more clear).Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y] ≠ s[p...q].

The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters. The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the i-th character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on. The third line of the input consists a single integer k (0 ≤ k ≤ |s|) — the maximum acceptable number of bad characters in a good substring.

Print a single integer — the number of distinct good substrings of string s.

NoteIn the first example there are following good substrings: "a", "ab", "b", "ba", "bab".In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".

object test5 extends App {
    val s=readLine
    val table=readLine.map(c=> if(c=='0') false else true) toArray
    val k=readInt
    val trie=new Trie(table,k)

    for(i<-0 until s.length){
        trie.insert(s,i)
    }
    println(trie.count)
}

class Node{
    val children=new Array[Node](26)
}

class Trie(table:Array[Boolean], k:Int){
    val root=new Node
    var count=0
    def insert(str:String, start:Int)={
        var score=0
        var node=root
        var i=start
        while(score<=k && i<str.length){
            val key=str(i)-'a'
            if(!table(key)) score+=1
            if(score<=k){
                if(node.children(key)==null){
                    node.children(key)=new Node
                    count+=1
                }
                node=node.children(key)
            }
            i+=1
        }
    }
}


The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn - 1 is the distance between the n - 1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.

The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces.

Print a single number — the length of the shortest path between stations number s and t.

NoteIn the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.

import scala.collection.mutable.ArrayBuffer
object A extends App {
  val n = readLine.toInt
  val t = for (s <- readLine.split(" ")) yield s.toInt
  val Array(_s,_g) = for(s <- readLine.split(" ")) yield s.toInt - 1

  def srt(a: Int, b: Int) = { if(a < b) (a,b) else (b,a) }
  val (s,g) = srt(_s, _g)

  def solve1(i: Int): Int = {
    if(i == g) 0
    else t(i) + solve1(i+1)
  }
  def solve2(i: Int): Int = {
    if(i == g) t(i)
    else t(i) + solve2((i-1+n)%n)
  }
  val (res,_) = srt(solve1(s),solve2((s-1+n)%n))
  println(res)
}

import java.util.StringTokenizer

object _278A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  val s = next.toInt - 1
  val t = next.toInt - 1
  if (s == t) println(0)
  else {
    def f(x: Int): Int =
      if (x == t) 0
      else f((x + 1) % n) + a(x)

    def g(x: Int): Int =
      if (x == t) 0
      else g((x + n - 1) % n) + a((x + n - 1) % n)

    println(f(s) min g(s))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val d = in.next().split(" ").map(_.toInt)
  val Array(s, t) = in.next().split(" ").map(_.toInt - 1).sorted
  val n1 = d.slice(s, s + t - s).sum
  val n2 = d.take(s).sum + d.drop(t).sum
  println(Math.min(n1, n2))

}

object A278 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val dist = readInts(n)
    var Array(s, t) = readInts(2)
    var clockWise = 0
    if (t >= s) {
      var loc = s
      while (loc != t) {
        clockWise += dist(loc - 1)
        loc += 1
      }
    } else {
      var loc = s
      while (loc != n + 1) {
        clockWise += dist(loc - 1)
        loc += 1
      }
      loc = 1
      while (loc != t) {
        clockWise += dist(loc - 1)
        loc += 1
      }
    }
    var antiClockWise = 0
    var temp = s
    s = t
    t = temp
    if (t >= s) {
      var loc = s
      while (loc != t) {
        antiClockWise += dist(loc - 1)
        loc += 1
      }
    } else {
      var loc = s
      while (loc != n + 1) {
        antiClockWise += dist(loc - 1)
        loc += 1
      }
      loc = 1
      while (loc != t) {
        antiClockWise += dist(loc - 1)
        loc += 1
      }
    }
    println(math.min(clockWise, antiClockWise))
  }

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

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

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

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

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

}

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

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

  val N = sc.nextInt
  val d = Array.fill(N)(sc.nextInt)
  val s, t = sc.nextInt

  val answer = {
    val d0 = {
      val s0 = s min t
      val t0 = s max t

      for (i <- s0 - 1 until t0 - 1)
      yield d(i)
    }.sum
    val d1 = d.sum - d0
    d0 min d1
  }

  out.println(answer)
  out.close
}

import annotation.tailrec
import java.io._

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

  val n = readInt
  val a = readInts
  val Array(s, t) = readInts
  val sum = a.zip(1 to n).filter {
    case (_, pos) => pos >= s.min(t) && pos < s.max(t)
  }.map(_._1).sum
  def ans = sum.min(a.sum - sum)

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

object Main {
  def main(args: Array[String]) {
    val num = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val ind = readLine().split(" ").map(_.toInt).sorted
    val direct = a.drop(ind(0) - 1).take(ind(1) - ind(0)).sum
    val indirect = a.sum - direct
    println(direct.min(indirect))
  }
}

import Array._

object main extends App with fastIO {

  var Array(n) = readLine split(" ") map(_.toInt)
  var a = readLine split(" ") map(_.toInt)
  var Array(s, t) = readLine split (" ") map(_.toInt) sorted

  val value = a.drop(s - 1).take(t - s).sum
  println((a.sum - value) min value)
  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 java.util.Scanner;
object runner {
def main(args:Array[String]){
var sc =new Scanner(System.in);
        var a=sc.nextInt();
       var i=0;
       val mas=new Array[Int](a);
       var sum=0;
        while(i<a)
        {
            mas(i)=sc.nextInt();
            sum+=mas(i);
            i+=1;
        }
        var j=sc.nextInt();
       var l=sc.nextInt();
        if(j>l){var k=j;j=l;l=k;}
       var x=0;
        if(j!=l){
        while(j<l)
        {
            x+=mas(j-1);
            j+=1;
        }
        System.out.println(Math.min(x,sum-x));}else{System.out.println(0);}
        }
    }

object runner {
def main(args:Array[String]){
var liner=readInt();
var read=readLine().split(" ");
var re=readLine().split(" ");
var first=re(0).toInt;
var second=re(1).toInt;
var sum=0;
for(i<-first-1 to second-2){
  sum+=read(i).toInt;
}
if(first==liner){
  var path=read(first-1).toInt;
  for(i<-second-1 to first-2){
    sum+=read(i).toInt;
  }
  if(sum>path){
    sum=path;
  }
}
println(sum);
}
}

object runner {
def main(args:Array[String]){
var liner=readInt();
var read=readLine().split(" ");
var re=readLine().split(" ");
var first=re(0).toInt;
var second=re(1).toInt;
var sum=0;
if(first<second){
for(i<-first-1 to second-2){
  sum+=read(i).toInt;
}
}else{
  for(i<-second-1 to first-2){
    sum+=read(i).toInt;
  }
  if(first==liner){
  var path=read(first-1).toInt;
  if(sum>path){
    sum=path;
  }
}

}

println(sum);
}
}


A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions:  Is it true that y is strictly larger than number x?  Is it true that y is strictly smaller than number x?  Is it true that y is larger than or equal to number x?  Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, "yes" or "no".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 10000) — the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: "sign x answer", where the sign is:   ">" (for the first type queries),  "<" (for the second type queries),  ">=" (for the third type queries),  "<=" (for the fourth type queries).  All values of x are integer and meet the inequation  - 109 ≤ x ≤ 109. The answer is an English letter "Y" (for "yes") or "N" (for "no"). Consequtive elements in lines are separated by a single space.

Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation  - 2·109 ≤ y ≤ 2·109. If there are many answers, print any of them. If such value doesn't exist, print word "Impossible" (without the quotes).

object Main {
  def main(args: Array[String]) {
    val n = readLine().toInt
    var left = -2000000000
    var right = 2000000000
    for (i <- 1 to n) {
      val Array(sign, x_str, answer) = readLine().split(' ')
      val x = x_str.toInt
      sign match {
        case ">" => {
          answer match {
            case "Y" => left = max(x + 1, left)
            case "N" => right = min(x, right)
          }
        }
        case ">=" => {
          answer match {
            case "Y" => left = max(x, left)
            case "N" => right = min(x - 1, right)
          }
        }
        case "<" => {
          answer match {
            case "Y" => right = min(x - 1, right)
            case "N" => left = max(x, left)
          }
        }
        case "<=" => {
          answer match {
            case "Y" => right = min(x, right)
            case "N" => left = max(x + 1, left)
          }
        }
      }
      if (left > right) {
        println("Impossible")
        return
      }
    }
    println(left)
  }

  def min(x: Int, y: Int) = if (x < y) x else y

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

object A extends App {
	val n = readInt()

	def negOp(op: String) = op match {
		case ">" => "<="
		case ">=" => "<"
		case "<" => ">="
		case "<=" => ">"
	}

	def guess(k: Int, mi: Int, ma: Int): Option[Int] = {
		if(mi > ma) None
		else if (k == 0) Some(mi)
		else {
			val line = readLine()
			val pat = """(>|>=|<|<=)\s(-?\d+)\s(Y|N)""".r
			val pat(op, num, ans) = line
			val op1 = if(ans == "N") negOp(op) else op
			val num1 = num.toInt
			op1 match {
				case ">" => guess(k - 1, math.max(mi, num1 + 1), ma)
				case ">=" => guess(k - 1, math.max(mi, num1), ma)
				case "<" => guess(k - 1, mi, math.min(ma, num1 - 1))
				case "<=" => guess(k - 1, mi, math.min(ma, num1))
			}
		}
	}

	guess(n, -2000000000, 2000000000) match {
		case Some(z) => println(z)
		case None => println("Impossible")
	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val (l, r) = (1 to n).foldLeft(-2l * 1E9.toLong, 2l * 1E9.toLong) {
    case ((left, right), _) if left > right => (left, right)
    case ((left, right), _) =>
      in.next().split(' ') match {
        case Array(">", b, "N") => (left, Math.min(right, b.toLong))
        case Array("<=", b, "Y") => (left, Math.min(right, b.toLong))
        case Array("<", b, "N") => (Math.max(left, b.toLong), right)
        case Array(">=", b, "Y") => (Math.max(left, b.toLong), right)
        case Array(">=", b, "N") => (left, Math.min(right, b.toLong - 1))
        case Array("<", b, "Y") => (left, Math.min(right, b.toLong - 1))
        case Array("<=", b, "N") => (Math.max(left, b.toLong + 1), right)
        case Array(">", b, "Y") => (Math.max(left, b.toLong + 1), right)
      }
  }
  if (l > r)
    println("Impossible")
  else
    println(l)
}

object Main {
  def main(args: Array[String]) {
    val n = readLine().toInt
    var left = -2000000001
    var right = 2000000001
    for (i <- 1 to n) {
      val Array(sign, x_str, answer) = readLine().split(' ')
      val x = x_str.toInt
      sign match {
        case ">" => {
          answer match {
            case "Y" => left = max(x + 1, left)
            case "N" => right = min(x, right)
          }
        }
        case ">=" => {
          answer match {
            case "Y" => left = max(x, left)
            case "N" => right = min(x - 1, right)
          }
        }
        case "<" => {
          answer match {
            case "Y" => right = min(x - 1, right)
            case "N" => left = max(x, left)
          }
        }
        case "<=" => {
          answer match {
            case "Y" => right = min(x, right)
            case "N" => left = max(x + 1, left)
          }
        }
      }
      if (left > right) {
        println("Impossible")
        return
      }
    }
    println(left)
  }

  def min(x: Int, y: Int) = if (x < y) x else y

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

object A extends App {
	val n = readInt()

	def negOp(op: String) = op match {
		case ">" => "<="
		case ">=" => "<"
		case "<" => ">="
		case "<=" => ">"
	}

	def guess(k: Int, mi: Int, ma: Int): Option[Int] = {
		if(mi > ma) None
		else if (k == 0) Some(mi)
		else {
			val line = readLine()
			val pat = """(>|>=|<|<=)\s(-?\d+)\s(Y|N)""".r
			val pat(op, num, ans) = line
			val op1 = if(ans == "N") negOp(op) else op
			val num1 = num.toInt
			op1 match {
				case ">" => guess(k - 1, num1 + 1, ma)
				case ">=" => guess(k - 1, num1, ma)
				case "<" => guess(k - 1, mi, num1 - 1)
				case "<=" => guess(k - 1, mi, num1)
			}
		}
	}

	guess(n, -2000000000, 2000000000) match {
		case Some(z) => println(z)
		case None => println("Impossible")
	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val (l, r) = (1 to n).foldLeft(-2l * 10E9.toLong, 2l * 10E9.toLong) {
    case ((left, right), _) if left > right => (left, right)
    case ((left, right), _) =>
      in.next().split(' ') match {
        case Array(">", b, "N") => (left, Math.min(right, b.toLong))
        case Array("<=", b, "Y") => (left, Math.min(right, b.toLong))
        case Array("<", b, "N") => (Math.max(left, b.toLong), right)
        case Array(">=", b, "Y") => (Math.max(left, b.toLong), right)
        case Array(">=", b, "N") => (left, Math.min(right, b.toLong - 1))
        case Array("<", b, "Y") => (left, Math.min(right, b.toLong - 1))
        case Array("<=", b, "N") => (Math.max(left, b.toLong + 1), right)
        case Array(">", b, "Y") => (Math.max(left, b.toLong + 1), right)
      }
  }
  if (l > r)
    println("Impossible")
  else
    println(l)
}


Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.

Print a single number — the number of distinct letters in Anton's set.

import scala.io.StdIn._

object Main extends App {
  val rgx = """\w""".r
  val input = readLine().split("")
  val chars = input.filter(rgx.pattern.matcher(_).matches())
  val ans = chars.toSet.size
  println(ans)
}

object Main extends App{
  val in=readLine
  println(in.filter(t => t >='a'&& t <='z').distinct.length)
}

import scala.io.StdIn

object Task443A {
	def main(args: Array[String]) {
		val s = StdIn.readLine()
		if (s.length == 2) println(0)
		else println(s.substring(1, s.length - 1).split(", ").toSet.size)
	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  println(in.next().filter(t => t >= 'a' && t <= 'z').distinct.length)
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println(readLine.drop(1).dropRight(1).split(",").filter(t=>t.trim.length!=0).map(_.trim).toSet.size)
  }
}

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

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

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

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

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

    println(input.drop(1).dropRight(1).split(", ").dropWhile(_.isEmpty).toSet.size)
  }
}

object AntonAndLetters {

	def main (args: Array[String]) {
  		val scanner = new java.util.Scanner(System.in);
  		val input = scanner.nextLine();
  		val inputAsArray = input.split(Array(',', ' ', '}','{'));
  		println(Math.max(0,inputAsArray.toSet.size-1));
	}
}

object Main extends App {
  override def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val str = cin.nextLine()
    def solve(c: Char, ans: Int): Int =
      if (c > 'z') ans
      else if (str.contains(c)) solve((c + 1).toChar, ans + 1)
      else solve((c + 1).toChar, ans)
    println(solve('a', 0))
  }
}

import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
    val s = readLine.toString.replaceAll("[{}, ]","")
    println(s.distinct.size)
  }
}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by Kuang.Ru on 14-9-17.
 */
object A443 extends App {
  val sc = new Scanner(System.in)
  val letters = sc.nextLine()
  val letterSet = new mutable.HashSet[Char]()

  letters.toCharArray.foreach((c: Char) => {
    if (c <= 'z' && c >= 'a') {
      letterSet += c
    }
  })

  println(letterSet.size)
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object AntonLetters {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

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

   def main(args: Array[String]) {
     val s = readLine
     if (s == "{}") println("0") else
     println(s.tail.reverse.tail.reverse.split(", ").toSet.size)

   }

}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    println(StdIn.readLine().filter(t => t >= 'a' && t <= 'z' ).distinct.length)

  }

}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    println(StdIn.readLine().
      replace("{","").replace("}", "").split(", ").
      map(_.toCharArray).flatten.toSet.size)

  }

}

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

object Solution extends App {
  val s = readLine.split("{}, ".toArray).filter(_!="")

  println(s.toSet.size)
}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
    val input = br.readLine()
  val r = input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',')
  if (r.isEmpty) println(0) else println(r.split(" ").toList.toSet.size)

}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println(readLine.drop(1).dropRight(1).split(",").map(_.trim).toSet.size)
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object AntonLetters {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

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

   def main(args: Array[String]) {
     println(readLine.tail.reverse.tail.reverse.split(", ").toSet.size)

   }

}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
  val input = br.readLine()
  println(input.filter(_ == '{').filter(_ == '}').split(" ").toList.toSet.size)

}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
  val input = br.readLine()
  println(input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',').split(" ").toList.toSet.size)

}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
    val input = br.readLine()
  val r = input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',')
  if (r.isEmpty) println(0) else r.split(" ").toList.toSet.size

}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
  val input = br.readLine()
  println(input.split(" ").toList.toSet.size - 2)

}


Ivan is collecting coins. There are only $$$N$$$ different collectible coins, Ivan has $$$K$$$ of them. He will be celebrating his birthday soon, so all his $$$M$$$ freinds decided to gift him coins. They all agreed to three terms:  Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than $$$L$$$ coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.

The only line of input contains 4 integers $$$N$$$, $$$M$$$, $$$K$$$, $$$L$$$ ($$$1 \le K \le N \le 10^{18}$$$; $$$1 \le M, \,\, L \le 10^{18}$$$) — quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.

Print one number — minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print "-1" (without quotes).

NoteIn the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins.

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, K, L = nl()
    val x = (L + K - 1) / M + 1
    if (x == 0 || BigInt(M) * x > N) {
      out.println(-1)
    } else {
      out.println(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 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
  }
}

object CF_518_2_A {
  def solve(N: Long, // number of coin types
            M: Long, // number of friends
            K: Long, // how many types Ivan has
            L: Long  // min number of new types
           ): Long = {
    val maxTypes = (N/M)*M
    val needed = K + L
    if (needed > maxTypes) -1
    else  Utility.longCeil(needed, M)

  }

  def main(args: Array[String]) = {
    val io = new IO(System.in)
    val solution = solve(io.long, io.long, io.long, io.long)
    println(solution)
  }

/// 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 long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a + b - 1) / b
      def longCeil(a: Long, b: Long) = (a + b - 1) / b
    }

}


The only difference between easy and hard versions is constraints.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive integers.Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $$$a$$$ and $$$b$$$, $$$a$$$ can be equal $$$b$$$) and is as follows: $$$[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$$$. There $$$x, y$$$ are integers greater than or equal to $$$0$$$. For example, sequences $$$[]$$$, $$$[2]$$$, $$$[1, 1]$$$, $$$[1, 2, 1]$$$, $$$[1, 2, 2, 1]$$$ and $$$[1, 1, 2, 1, 1]$$$ are three block palindromes but $$$[1, 2, 3, 2, 1]$$$, $$$[1, 2, 1, 2, 1]$$$ and $$$[1, 2]$$$ are not.Your task is to choose the maximum by length subsequence of $$$a$$$ that is a three blocks palindrome.You have to answer $$$t$$$ independent test cases.Recall that the sequence $$$t$$$ is a a subsequence of the sequence $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$s=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.

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$$$ ($$$1 \le n \le 2000$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 26$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. Note that the maximum value of $$$a_i$$$ can be up to $$$26$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each test case, print the answer — the maximum possible length of some subsequence of $$$a$$$ that is a three blocks palindrome.

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

object Solution_E1 extends App {

  val T = StdIn.readInt()
  for (_ <- 1 to T) {
    val N = StdIn.readInt()
    val array = StdIn.readLine().split(' ').map{_.toInt}
    val distinct = mutable.SortedSet[Int]()
    array foreach {x => distinct.add(x)}
    val distArray = distinct.toArray
    var result = 1
    val M = 200
    val sumsRight = Array.fill[Int](M+1, N)(0)
    val sumsLeft = Array.fill[Int](M+1, N)(0)
    sumsRight(array.last)(N - 1) = 1
    sumsLeft(array.head)(0) = 1
    for (idx <- N - 2 to 0 by -1) {
       for (j <- 1 to M) {
         sumsRight(j)(idx) = sumsRight(j)(idx + 1)
       }
      sumsRight(array(idx))(idx) += 1
    }
    for (idx <- 1 until N) {
      for (j <-1 to M) {
        sumsLeft(j)(idx) = sumsLeft(j)(idx - 1)
      }
      sumsLeft(array(idx))(idx) += 1
    }
    for (startY <- 1 until N - 1) {
      for (endY <- startY until N - 1) {
        var Y = 1
        distArray foreach { x =>
          val current = sumsRight(x)(startY) - sumsRight(x)(endY + 1)
          Y = Math.max(Y, current)
        }
        distArray foreach { x =>
          result = Math.max(result, Y + 2 * Math.min(sumsLeft(x)(startY-1), sumsRight(x)(endY + 1)))
        }
      }
    }
    val distinctM = Array.fill[Int](M + 1)(0)
    array foreach {x => distinctM(x) += 1}
    result = Math.max(result, distinctM.max)
    println(result)
  }
}

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

object Solution_E1 extends App {

  val T = StdIn.readInt()
  for (_ <- 1 to T) {
    StdIn.readInt()
    val array = StdIn.readLine().split(' ').map{_.toInt}
    val distinct = mutable.SortedSet[Int]()
    array foreach {x => distinct.add(x)}
    val distArray = distinct.toArray
    var result = 1
    for (a <- 0 until distArray.size) {
      for (b <- a + 1 until distArray.size) {
        val filteredArray = array.filter(x => x == distArray(a) || x == distArray(b))
        val N = filteredArray.length
        val repeatRight = Array.fill[Int](N)(1)
        val repeatLeft = Array.fill[Int](N)(1)
        for (idx <- N - 2 to 0 by -1) {
           val next = if (filteredArray(idx) == filteredArray(idx + 1)) {
            repeatRight(idx + 1) + 1
          } else {
            1
          }
          repeatRight(idx) = next
        }
        for (idx <- 1 until N) {
          repeatLeft(idx) = if (filteredArray(idx) == filteredArray(idx - 1)) {
            repeatLeft(idx - 1) + 1
          } else {
            1
          }
        }
        for (idx <- 0 until N) {
          val y = repeatRight(idx)
          val xLeft = if (idx > 0) {
            repeatLeft(idx - 1)
          } else {
            0
          }
          val xRight = if (idx + y < N) {
            repeatRight(idx + y)
          } else {
            0
          }
          result = Math.max(result, y)
          if (xLeft > 0 && xRight > 0) {
            if (filteredArray(idx - 1) == filteredArray (idx + y)) {
              val total = y + 2 * Math.min(xLeft, xRight)
              result = Math.max(result, total)
            }
          }
        }
      }
    }
    val distinctM = Array.fill[Int](201)(0)
    array foreach {x => distinctM(x) += 1}
    result = Math.max(result, distinctM.max)
    println(result)
  }
}

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

object Solution_E1 extends App {

  val T = StdIn.readInt()
  for (_ <- 1 to T) {
    val N = StdIn.readInt()
    val array = StdIn.readLine().split(' ').map{_.toInt}
    val distinct = mutable.SortedSet[Int]()
    array foreach {x => distinct.add(x)}
    val distArray = distinct.toArray
    var result = 1
    for (a <- 0 until distArray.size) {
      for (b <- a + 1 until distArray.size) {
        val filteredArray = array.filter(x => x == distArray(a) || x == distArray(b))
        val N = filteredArray.length
        val repeatRight = Array.fill[Int](N)(1)
        val repeatLeft = Array.fill[Int](N)(1)
        for (idx <- N - 2 to 0 by -1) {
           val next = if (filteredArray(idx) == filteredArray(idx + 1)) {
            repeatRight(idx + 1) + 1
          } else {
            1
          }
          repeatRight(idx) = next
        }
        for (idx <- 1 until N) {
          repeatLeft(idx) = if (filteredArray(idx) == filteredArray(idx - 1)) {
            repeatLeft(idx - 1) + 1
          } else {
            1
          }
        }
        for (idx <- 0 until N) {
          val y = repeatRight(idx)
          val xLeft = if (idx > 0) {
            repeatLeft(idx - 1)
          } else {
            0
          }
          val xRight = if (idx + y < N) {
            repeatRight(idx + y)
          } else {
            0
          }
          result = Math.max(result, y)
          if (xLeft > 0 && xRight > 0) {
            if (repeatLeft(idx - 1) == repeatRight(idx + y)) {
              val total = y + 2 * Math.min(xLeft, xRight)
              result = Math.max(result, total)
            }
          }
        }
      }
    }
    val distinctM = Array.fill[Int](201)(0)
    array foreach {x => distinctM(x) += 1}
    result = Math.max(result, distinctM.max)
    println(result)
  }
}


Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches. The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.

Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.

NoteIn the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()
  val red = line.count(_ == 'r')
  val black = n - red
  val redOdd = line.indices.count(i => i % 2 == 1 && line(i) == 'r')
  val redEven = red - redOdd
  val blackOdd = line.indices.count(i => i % 2 == 1 && line(i) == 'b')
  val blackEven = black - blackOdd
  val redFirst = Math.max(redOdd, blackEven)
  val blackFirst = Math.max(blackOdd, redEven)
  println(Math.min(redFirst, blackFirst))
}

import scala.io.StdIn._
object ProblemB extends App {
  val n = readInt()
  val s = readLine().view.zipWithIndex

  val rb = s.foldLeft((0, 0))((acc, t) =>
    (if ((t._2 % 2 == 0 && t._1 == 'r') || t._2 % 2 == 1) acc._1 else acc._1 + 1,
    if ((t._2 % 2 == 1 && t._1 == 'b') || t._2 % 2 == 0) acc._2 else acc._2 + 1)
  )

  val rb2 = s.foldLeft((0, 0))((acc, t) =>
    (if ((t._2 % 2 == 0 && t._1 == 'b') || t._2 % 2 == 1) acc._1 else acc._1 + 1,
      if ((t._2 % 2 == 1 && t._1 == 'r') || t._2 % 2 == 0) acc._2 else acc._2 + 1)
  )

  val solution1 = math.abs(rb._1 - rb._2) + math.min(rb._1, rb._2)
  val solution2 = math.abs(rb2._1 - rb2._2) + math.min(rb2._1, rb2._2)
  println(math.min(solution1, solution2))
}


Given a positive integer $$$k$$$, two arrays are called $$$k$$$-similar if:  they are strictly increasing;  they have the same length;  all their elements are positive integers between $$$1$$$ and $$$k$$$ (inclusive);  they differ in exactly one position. You are given an integer $$$k$$$, a strictly increasing array $$$a$$$ and $$$q$$$ queries. For each query, you are given two integers $$$l_i \leq r_i$$$. Your task is to find how many arrays $$$b$$$ exist, such that $$$b$$$ is $$$k$$$-similar to array $$$[a_{l_i},a_{l_i+1}\ldots,a_{r_i}]$$$.

The first line contains three integers $$$n$$$, $$$q$$$ and $$$k$$$ ($$$1\leq n, q \leq 10^5$$$, $$$n\leq k \leq 10^9$$$) — the length of array $$$a$$$, the number of queries and number $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots,a_n$$$ ($$$1 \leq a_i \leq k$$$). This array is strictly increasing  — $$$a_1 < a_2 < \ldots < a_n$$$. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$).

Print $$$q$$$ lines. The $$$i$$$-th of them should contain the answer to the $$$i$$$-th query.

NoteIn the first example:In the first query there are $$$4$$$ arrays that are $$$5$$$-similar to $$$[2,4]$$$: $$$[1,4],[3,4],[2,3],[2,5]$$$.In the second query there are $$$3$$$ arrays that are $$$5$$$-similar to $$$[4,5]$$$: $$$[1,5],[2,5],[3,5]$$$.

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader

object BReplaceandKeepSorted {
  def solve(k: Int, initList: Array[Int], s: Int, f: Int): Int = {
    if (s == f) return k - 1
//    var c = 0
//    for (i <- s until f - 1) {
//      c += (initList(i+1) - initList(i-1) - 2)
//    }
//    c + (initList(s) - 2) + (k + 1 - initList(f - 2) - 2)
    (f - s + 1) * (-2) + k + 1 + initList(f - 1) - initList(s-1)
  }

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//            val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//              ("6 5 10\n2 4 6 7 8 9\n1 4\n1 2\n3 5\n1 6\n5 5").getBytes)))
    val n::q::k::Nil = file.readLine.split(" ").map(_.toInt).toList
    val as = file.readLine.split(" ").map(_.toInt)
    var i = 0
    while (i < q) {
      val l::r::Nil = file.readLine.split(" ").map(_.toInt).toList
      println(solve(k, as, l, r))
      i += 1
    }
  }
}

object Main {
    def main(args: Array[String]) = {
        val Array(n, q, k) = readLine().split("\\s+").map(_.toInt)
        val a = readLine().split("\\s+").map(_.toInt)
        for (i <- 1 to q){
            // val l = sc.nextInt()
            // val r = sc.nextInt()
            var Array(l, r) = readLine().split("\\s+").map(_.toInt)
            l -= 1
            r -= 1
            val len = r - l + 1
            println((k - len) * 2 - (a(l) - 1) - (k - a(r)))
            // println(k - r + l)
        }
    }
}


Phoenix is playing with a new puzzle, which consists of $$$n$$$ identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.    A puzzle piece The goal of the puzzle is to create a square using the $$$n$$$ pieces. He is allowed to rotate and move the pieces around, but none of them can overlap and all $$$n$$$ pieces must be used (of course, the square shouldn't contain any holes as well). Can he do it?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of puzzle pieces.

For each test case, if Phoenix can create a square with the $$$n$$$ puzzle pieces, print YES. Otherwise, print NO.

NoteFor $$$n=2$$$, Phoenix can create a square like this:    For $$$n=4$$$, Phoenix can create a square like this:    For $$$n=6$$$, it is impossible for Phoenix to create a square.

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

    for (_ <- 1 to nextInt) {
      val n = nextLong
      var ok = false
      if (n % 2 == 0) {
        val m = n / 2
        val s = Math.sqrt(m).toInt
        if (s * s == m) ok = true
      }
      if (n % 4 == 0) {
        val m = n / 4
        val s = Math.sqrt(m).toInt
        if (s * s == m) ok = true
      }

      out.println(if (ok) "YES" else "NO")
    }

    out.flush()
  }

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