Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of juices. Each of the next $$$n$$$ lines contains an integer $$$c_i$$$ $$$(1 \le c_i \le 100\,000)$$$ and a string $$$s_i$$$ — the price of the $$$i$$$-th juice and the vitamins it contains. String $$$s_i$$$ contains from $$$1$$$ to $$$3$$$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $$$s_i$$$. The order of letters in strings $$$s_i$$$ is arbitrary.

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

NoteIn the first example Petya buys the first, the second and the fourth juice. He spends $$$5 + 6 + 4 = 15$$$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $$$16$$$, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".

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 Inf = 1e7.toInt
    val map = mutable.Map[String, Int]() withDefaultValue Inf

    rep(N) { _ =>
      val v = ni()
      val vit = ns().sorted
      if (v < map(vit)) map(vit) = v
    }

    val vals = map map {
      case ("A", v) => min(map("B") + map("C"), map("BC")) + v
      case ("B", v) => min(map("A") + map("C"), map("AC")) + v
      case ("C", v) => min(map("A") + map("B"), map("AB")) + v
      case ("AB", v) => min(min(map("C"), map("AC")), map("BC")) + v
      case ("AC", v) => min(min(map("B"), map("AB")), map("BC")) + v
      case ("BC", v) => min(min(map("A"), map("AB")), map("AC")) + v
      case ("ABC", v) => v
    }

    val ans = vals.min

    out.println(if (ans >= Inf) -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): 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
  }
}


You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5; 1 \le m \le 10^5$$$) — the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \le s_j, t_j \le n; s_j \ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.

Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val m = tokenizer.nextToken().toInt
    val q = tokenizer.nextToken().toInt
    val C = new Array[Long](m)
    tokenizer = new StringTokenizer(input.readLine())
    for (i <- 1 to m) {
      C(i-1) = tokenizer.nextToken().toLong
    }
    val B = new Array[Long](m)
    val A = new Array[Long](m)
    A(0) = 0
    B(m-1) = 0
    for (i <- 1 to m-1) {
        A(i) = A(i-1) + max(0,C(i-1) - C(i))
        B(m-1-i) = B(m-1-i+1) + max(0,C(m-1-i+1) - C(m-1-i))
    }
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n1 = tokenizer.nextToken().toInt
      val n2 = tokenizer.nextToken().toInt
      if (n1 < n2) {
        println(A(n2-1) - A(n1-1))
      }
      else {
        println(B(n2-1) - B(n1-1))
      }
    }
  }
}

import scala.io.StdIn._
import scala.util.control.Breaks._

object Main {
  def main(args: Array[String]): Unit = {
      val Array(n, m): Array[Int] = readLine().split(" ").map(_.toInt)
      val A: Array[Long]  = readLine().split(" ").map(_.toLong)
      val pref: Array[Long] = Array.fill(n)(0)
      val suff: Array[Long] = Array.fill(n)(0)
      for (i <- 1 until n) {
          pref(i) = pref(i-1) - (A(i) - A(i-1)).min(0)
      }
      for (i <- n-2 to 0 by -1) {
          suff(i) = suff(i+1) - (A(i) - A(i+1)).min(0)
      }

      for (_ <- 1 to m) {
          val Array(s, t) = readLine().split(" ").map(x => x.toInt-1)
          if (s == t) {
              println(0)
          } else if (s < t) {
              println(pref(t)-pref(s))
          } else {
              println(suff(t)-suff(s))
          }
      }
    }
}


Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

First of line of input contains a single number $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length $$$n$$$, containing symbols "(" and ")".

Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".

NoteIn the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.In the second example, there is no way to move at most one bracket so that the sequence becomes correct.In the third example, the sequence is already correct and there's no need to move brackets.

object C {

  def main(args: Array[String]): Unit = {}
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val s = readLine

  var x = 0
  var ok = true
  for (c <- s) {
    if (c == '(') x += 1 else x -= 1
    if (x < -1) ok = false
  }

  val res = ok && x == 0
  println(if (res) "Yes" else "No")
}


Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or  - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di =  - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.

The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected.

Print  - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1.

NoteIn the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.

import scala.collection.mutable

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = {
    val tl = tokenizeLine
    val a = Array.ofDim[Int](n)
    var i = 0
    while (i < n) {
      a(i) = Integer.parseInt(tl.nextToken)
      i += 1
    }
    a
  }

  val Array(n, m) = readInts(2)
  val ds = readInts(n)

  val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (id <- 1 to m) {
    val Array(_u, _v) = readInts(2)
    val u = _u - 1
    val v = _v - 1

    adjBuilders(u) += v
    adjBuilders(v) += u

    edgeIdBuilders(u) += id
    edgeIdBuilders(v) += id
  }

  val firstMinus = ds.indexOf(-1)
  val sumParity = ds.count(_ == 1) % 2

  if (firstMinus == -1 && sumParity == 1) {
    println(-1)
  } else {

    for (i <- ds.indices) {
      if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0
    }

    val adjs = adjBuilders.map(_.result)
    val edgeIds = edgeIdBuilders.map(_.result)

    val visited = new mutable.BitSet(n)
    val leaves = mutable.Queue.empty[Int]
    val childrenCounts = Array.fill(n)(0)
    val parents, parentEdges = Array.fill(n)(-1)

    def dfs(u: Int): Unit = {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val v = adjs(u)(i)
        if (!visited(v)) {
          childrenCounts(u) += 1
          parents(v) = u
          parentEdges(v) = edgeIds(u)(i)
          dfs(v)
        }
        i += 1
      }
      if (childrenCounts(u) == 0) leaves += u
    }

    dfs(0)

    val resultBuilder = new mutable.ArrayBuilder.ofInt

    while (leaves.nonEmpty) {
      val u = leaves.dequeue()
      val v = parents(u)
      if (v >= 0) {

        if (ds(u) == 1) {
          resultBuilder += parentEdges(u)
          ds(v) = 1 - ds(v)
        }
        childrenCounts(v) -= 1
        if (childrenCounts(v) == 0) leaves += v
      }
    }

    val res = resultBuilder.result

    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    println(res.length)
    println(res.sorted.mkString("\n"))
    Console.flush
  }
}

import scala.collection.mutable

object B extends App {

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

  val Array(n, m) = readInts(2)
  val ds = readInts(n)

  val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (id <- 1 to m) {
    val Array(_u, _v) = readInts(2)
    val u = _u - 1
    val v = _v - 1

    adjBuilders(u) += v
    adjBuilders(v) += u

    edgeIdBuilders(u) += id
    edgeIdBuilders(v) += id
  }

  val firstMinus = ds.indexOf(-1)
  val sumParity = ds.count(_ == 1) % 2

  if (firstMinus == -1 && sumParity == 1) {
    println(-1)
  } else {

    for (i <- ds.indices) {
      if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0
    }

    val adjs = adjBuilders.map(_.result)
    val edgeIds = edgeIdBuilders.map(_.result)

    val visited = new mutable.BitSet(n)
    val leaves = mutable.Queue.empty[Int]
    val childrenCounts = Array.fill(n)(0)
    val parents, parentEdges = Array.fill(n)(-1)

    def dfs(u: Int): Unit = {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val v = adjs(u)(i)
        if (!visited(v)) {
          childrenCounts(u) += 1
          parents(v) = u
          parentEdges(v) = edgeIds(u)(i)
          dfs(v)
        }
        i += 1
      }
      if (childrenCounts(u) == 0) leaves += u
    }

    dfs(0)

    val resultBuilder = new mutable.ArrayBuilder.ofInt

    while (leaves.nonEmpty) {
      val u = leaves.dequeue()
      val v = parents(u)
      if (v >= 0) {

        if (ds(u) == 1) {
          resultBuilder += parentEdges(u)
          ds(v) = 1 - ds(v)
        }
        childrenCounts(v) -= 1
        if (childrenCounts(v) == 0) leaves += v
      }
    }

    val res = resultBuilder.result

    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    println(res.length)
    println(res.sorted.mkString("\n"))
    Console.flush
  }
}

import scala.collection.mutable

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 ds = readInts(n)

  val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (id <- 1 to m) {
    val Array(_u, _v) = readInts(2)
    val u = _u - 1
    val v = _v - 1

    adjBuilders(u) += v
    adjBuilders(v) += u

    edgeIdBuilders(u) += id
    edgeIdBuilders(v) += id
  }

  val firstMinus = ds.indexOf(-1)
  val sumParity = ds.count(_ == 1) % 2

  if (firstMinus == -1 && sumParity == 1) {
    println(-1)
  } else {

    for (i <- ds.indices) {
      if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0
    }

    val adjs = adjBuilders.map(_.result)
    val edgeIds = edgeIdBuilders.map(_.result)

    val visited = new mutable.BitSet(n)
    val leaves = mutable.Queue.empty[Int]
    val childrenCounts = Array.fill(n)(0)
    val parents, parentEdges = Array.fill(n)(-1)

    def dfs(u: Int): Unit = {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val v = adjs(u)(i)
        if (!visited(v)) {
          childrenCounts(u) += 1
          parents(v) = u
          parentEdges(v) = edgeIds(u)(i)
          dfs(v)
        }
        i += 1
      }
      if (childrenCounts(u) == 0) leaves += u
    }

    dfs(0)

    val resultBuilder = new mutable.ArrayBuilder.ofInt

    while (leaves.nonEmpty) {
      val u = leaves.dequeue()
      val v = parents(u)
      if (v >= 0) {

        if (ds(u) == 1) {
          resultBuilder += parentEdges(u)
          ds(v) = 1 - ds(v)
        }
        childrenCounts(v) -= 1
        if (childrenCounts(v) == 0) leaves += v
      }
    }

    val res = resultBuilder.result

    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    println(res.length)
    println(res.sorted.mkString("\n"))
    Console.flush
  }
}

import scala.collection.mutable

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 ds = readInts(n)

  val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (id <- 1 to m) {
    val Array(_u, _v) = readInts(2)
    val u = _u - 1
    val v = _v - 1
    adjBuilders(u) += v
    adjBuilders(v) += u
    edgeIdBuilders(u) += id
    edgeIdBuilders(v) += id
  }

  val adjs = adjBuilders.map(_.result)
  val edgeIds = edgeIdBuilders.map(_.result)

  val checked = new mutable.BitSet(m)
  val resultBuilder = new mutable.ArrayBuilder.ofInt

  def dfs(u: Int): Unit = {
    var i = 0
    while (i < adjs(u).length) {
      val edgeId = edgeIds(u)(i)
      val v = adjs(u)(i)
      if (!checked(edgeId)) {
        checked(edgeId) = true
        if (ds(u) == 1 || ds(v) == 1) {
          resultBuilder += edgeId
          if (ds(u) != -1) ds(u) = 1 - ds(u)
          if (ds(v) != -1) ds(v) = 1 - ds(v)
        }
        dfs(v)
      }
      i += 1
    }
  }

  dfs(0)

  val res = resultBuilder.result
  val ok = !ds.contains(1)

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

  if (ok) {
    println(res.length)
    println(res.sorted.mkString("\n"))
  } else {
    println(-1)
  }

  Console.flush
}


You are given two strings $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. Also you have a string $$$z$$$ which is initially empty. You want string $$$z$$$ to be equal to string $$$t$$$. You can perform the following operation to achieve this: append any subsequence of $$$s$$$ at the end of string $$$z$$$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if $$$z = ac$$$, $$$s = abcde$$$, you may turn $$$z$$$ into following strings in one operation:   $$$z = acace$$$ (if we choose subsequence $$$ace$$$);  $$$z = acbcd$$$ (if we choose subsequence $$$bcd$$$);  $$$z = acbce$$$ (if we choose subsequence $$$bce$$$). Note that after this operation string $$$s$$$ doesn't change.Calculate the minimum number of such operations to turn string $$$z$$$ into string $$$t$$$.

The first line contains the integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The first line of each testcase contains one string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) consisting of lowercase Latin letters. The second line of each testcase contains one string $$$t$$$ ($$$1 \le |t| \le 10^5$$$) consisting of lowercase Latin letters. It is guaranteed that the total length of all strings $$$s$$$ and $$$t$$$ in the input does not exceed $$$2 \cdot 10^5$$$.

For each testcase, print one integer — the minimum number of operations to turn string $$$z$$$ into string $$$t$$$. If it's impossible print $$$-1$$$.

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val tb = stdin.next().toInt
  println(stdin.take(tb * 2).grouped(2).map(_.toArray).map(solve).mkString("\n"))

  def solve(arr: Array[String]): Int = {
    val Array(s, t) = arr
    val cache = Array.fill[Int](s.length, 26)(-1)
    s.zipWithIndex.foreach{
      case (ch, index) =>
        Range(index, -1, -1).takeWhile(i => cache(i)(ch - 'a') == -1).foreach(i => cache(i)(ch - 'a') = index)
    }
//    cache.foreach(i => println(i.mkString(" ")))
    val hasSolution = t.distinct.forall(ch => cache(0)(ch - 'a') != -1)
    if (!hasSolution) -1
    else {
      var matched = 0
      var lookCh = t.head
      var steps = 0
      while (matched < t.length) {
        var pos = 0
        steps += 1
        while (pos < s.length && cache(pos)(lookCh - 'a') != -1) {
          while (cache(pos)(lookCh - 'a') != pos && cache(pos)(lookCh - 'a') != -1)
            pos = cache(pos)(lookCh - 'a')
          if (cache(pos)(lookCh - 'a') != -1) {
            pos += 1
            matched += 1
            if (matched < t.length)
              lookCh = t.charAt(matched)
          }
        }
      }
      steps
    }
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val m = Array.fill(30)(Array.fill(100001)(0))
    val count = Array.fill(30)(0)
    val in = new InputReader(inputStream)
    val cases = in.nextInt()

    (1 to cases).foreach { _ =>
      val s = in.next()
      val t = in.next()
      (0 until 30).foreach(i => count(i) = 0)
      s.zipWithIndex.foreach{
        case (ch,i) => {
          val indxChar = (ch.toInt)- 'a'.toInt
          m(indxChar)(count(indxChar)) = i
          count(indxChar) = count(indxChar) + 1
        }
      }

      var sIndex = 0
      var tIndex = 0
      val maxSteps = t.length+1
      var steps = 1
      while(steps < maxSteps && (tIndex < t.length)){

        val ch = t.charAt(tIndex).toInt-'a'.toInt

        calcIndex(m,count,ch,sIndex) match {
          case Some(newSIndex) => {
            tIndex += 1
            sIndex = newSIndex+1
          }
          case None => {
            steps += 1
            sIndex = 0
          }
        }
      }
      if(tIndex == t.length){
        out.println(steps)
      }else{
        out.println(-1)
      }
    }

  }
  def calcIndex(m: Array[Array[Int]], count: Array[Int],a: Int, i: Int): Option[Int] = {
    val l = count(a)
    if(l == 0) {
      None
    } else{
      if(m(a)(l-1) < i) {

        None
      } else
        Some(calcIndex(m(a),l-1,i))
    }
  }
  def calcIndex(list: Array[Int], maxL: Int, i: Int): Int= {
    var left = 0
    var right = maxL
    //se asegura que list[right] <= i
    while(right - left > 1){
      val k = (left+right)/2
      if(list(k) < i){
        left = k
      }else{
        right = k
      }
    }
    if(list(left) >= i)
      list(left)
    else
      list(right)
  }

  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val m = Array.fill(30)(ListBuffer.empty[Int])
    val in = new InputReader(inputStream)
    val cases = in.nextInt()

    (1 to cases).foreach { _ =>
      val s = in.next()
      val t = in.next()
      m.foreach(_.clear())
      s.zipWithIndex.foreach{
        case (ch,i) => {
          val indxChar = (ch.toInt)- 'a'.toInt
          m(indxChar).append(i)
        }
      }

      var sIndex = 0
      var tIndex = 0
      val maxSteps = t.length+1
      var steps = 1
      while(steps < maxSteps && (tIndex < t.length)){

        val ch = t.charAt(tIndex).toInt-'a'.toInt

        calcIndex(m,ch,sIndex) match {
          case Some(newSIndex) => {
            tIndex += 1
            sIndex = newSIndex+1
          }
          case None => {
            steps += 1
            sIndex = 0
          }
        }
      }
      if(tIndex == t.length){
        out.println(steps)
      }else{
        out.println(-1)
      }
    }

  }
  def calcIndex(m: Array[ListBuffer[Int]],a: Int, i: Int): Option[Int] = {
    val l = m(a)
    if(l.isEmpty) {
      None
    } else{
      if(l.last < i) {

        None
      } else
        Some(calcIndex(l,i))
    }
  }
  def calcIndex(list: ListBuffer[Int], i: Int): Int= {
    var left = 0
    var right = list.length-1
    //se asegura que list[right] <= i
    while(right - left > 1){
      val k = (left+right)/2
      if(list(k) < i){
        left = k
      }else{
        right = k
      }
    }
    list(right)
  }

  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


Nezzar's favorite digit among $$$1,\ldots,9$$$ is $$$d$$$. He calls a positive integer lucky if $$$d$$$ occurs at least once in its decimal representation. Given $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$, for each $$$1 \le i \le q$$$ Nezzar would like to know if $$$a_i$$$ can be equal to a sum of several (one or more) lucky numbers.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 9$$$) — the number of test cases. The first line of each test case contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q \le 10^4$$$, $$$1 \le d \le 9$$$). The second line of each test case contains $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$ ($$$1 \le a_i \le 10^9$$$).

For each integer in each test case, print "YES" in a single line if $$$a_i$$$ can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower).

YES
NO
YES
YES
YES
NO
YES
YES
YES
YES
YES
YES
NO

NoteIn the first test case, $$$24 = 17 + 7$$$, $$$27$$$ itself is a lucky number, $$$25$$$ cannot be equal to a sum of lucky numbers.

object CF1478B {
  def readIntArr(): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt).toArray

  def main(args: Array[String]): Unit = {
    var T = scala.io.StdIn.readInt()
    for (t <- 0 until T) {
      var qd = readIntArr()
      var q = qd(0)
      var d = qd(1)

      var dp = new Array[Boolean](10 * d)
      dp(0) = true
      for (i <- 0 until 10 * d) {
        for (j <- 0 until d) {
          if (i + 10 * j + d < 10 * d)
            dp(i + 10 * j + d) |= dp(i)
        }
      }

      var u = readIntArr()
      for (i <- 0 until q) {
        if (u(i) >= 10 * d || dp(u(i))) {
          println("YES")
        } else println("NO")
      }
    }
  }
}


You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?

The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.

Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.

NoteCells, reachable in the corresponding example, are marked with '+'.First example:  +++..+***.+++***+++. Second example:  .++..+*..++..++.

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 H, W = ni()
    val r, c = ni() - 1
    val L, R = ni()
    val grid = Array.ofDim[Array[Boolean]](H)
    rep(H) { i =>
      grid(i) = ns(W) map (_ == '.')
    }

    val INF = 1e9.toInt
    val D = Array.fill[Int](H, W)(INF)

    case class Coord(h: Int, w: Int)

    def valid(h: Int, w: Int): Boolean = {
      0 <= h && h < H && 0 <= w && w < W && grid(h)(w)
    }

    case class Direction(dh: Int, dw: Int, weight: Int)
    val directions = Array(
      Direction(0, -1, 1),
      Direction(0, 1, 1),
      Direction(-1, 0, 0),
      Direction(1, 0, 0)
    )

    def ok(h: Int, w: Int, cost: Int) = {
      val extraCost = cost - abs(w - c)
      val l = extraCost / 2 + max(c - w, 0)
      val r = extraCost / 2 + max(w - c, 0)
      l <= L && r <= R
    }
    var ans = 1
    def dijk() = {
      case class Visit(v: Coord, cost: Int) extends Comparable[Visit] {
        override def compareTo(o: Visit): Int = java.lang.Integer.compare(cost, o.cost)
      }
      val queue = new java.util.LinkedList[Visit]()
      D(r)(c) = 0
      queue.add(Visit(Coord(r, c), 0))

      while(!queue.isEmpty) {
        val v = queue.pollFirst()
        if (D(v.v.h)(v.v.w) == v.cost) {
          rep(4) { i =>
            val d = directions(i)
            val h1 = v.v.h + d.dh
            val w1 = v.v.w + d.dw
            if (valid(h1, w1) && ok(h1, w1, v.cost + d.weight)) {
              val next = v.cost + d.weight
              if (D(h1)(w1) > next) {
                ans += 1
                D(h1)(w1) = next
                if (d.weight == 0) {
                  queue.addFirst(Visit(Coord(h1, w1), next))
                } else {
                  queue.addLast(Visit(Coord(h1, w1), next))
                }
              }
            }
          }
        }
      }
    }

    dijk()

    out.println(ans)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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 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 H, W = ni()
    val r, c = ni() - 1
    val L, R = ni()
    val grid = Array.ofDim[Array[Boolean]](H)
    rep(H) { i =>
      grid(i) = ns(W) map (_ == '.')
    }

    val INF = 1e9.toInt
    val D = Array.fill[Int](H, W)(INF)

    case class Coord(h: Int, w: Int)

    def valid(h: Int, w: Int): Boolean = {
      0 <= h && h < H && 0 <= w && w < W && grid(h)(w)
    }

    case class Direction(dh: Int, dw: Int, weight: Int)
    val directions = Array(
      Direction(0, -1, 1),
      Direction(0, 1, 1),
      Direction(-1, 0, 0),
      Direction(1, 0, 0)
    )

    def ok(h: Int, w: Int, cost: Int) = {
      val extraCost = cost - abs(w - c)
      val l = extraCost / 2 + max(c - w, 0)
      val r = extraCost / 2 + max(w - c, 0)
      l <= L && r <= R
    }
    var ans = 1
    def dijk() = {
      case class Visit(v: Coord, cost: Int) extends Comparable[Visit] {
        override def compareTo(o: Visit): Int = java.lang.Integer.compare(cost, o.cost)
      }
      val queue = new java.util.ArrayDeque[Visit]()
      D(r)(c) = 0
      queue.add(Visit(Coord(r, c), 0))

      while(!queue.isEmpty) {
        val v = queue.pollFirst()
        if (D(v.v.h)(v.v.w) == v.cost) {
          rep(4) { i =>
            val d = directions(i)
            val h1 = v.v.h + d.dh
            val w1 = v.v.w + d.dw
            if (valid(h1, w1) && ok(h1, w1, v.cost + d.weight)) {
              val next = v.cost + d.weight
              if (D(h1)(w1) > next) {
                ans += 1
                D(h1)(w1) = next
                if (d.weight == 0) {
                  queue.addFirst(Visit(Coord(h1, w1), next))
                } else {
                  queue.addLast(Visit(Coord(h1, w1), next))
                }
              }
            }
          }
        }
      }
    }

    dijk()

    out.println(ans)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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
  }
}


Recently Vova found $$$n$$$ candy wrappers. He remembers that he bought $$$x$$$ candies during the first day, $$$2x$$$ candies during the second day, $$$4x$$$ candies during the third day, $$$\dots$$$, $$$2^{k-1} x$$$ candies during the $$$k$$$-th day. But there is an issue: Vova remembers neither $$$x$$$ nor $$$k$$$ but he is sure that $$$x$$$ and $$$k$$$ are positive integers and $$$k > 1$$$.Vova will be satisfied if you tell him any positive integer $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$. It is guaranteed that at least one solution exists. Note that $$$k > 1$$$.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 one integer $$$n$$$ ($$$3 \le n \le 10^9$$$) — the number of candy wrappers Vova found. It is guaranteed that there is some positive integer $$$x$$$ and integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.

Print one integer — any positive integer value of $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.

NoteIn the first test case of the example, one of the possible answers is $$$x=1, k=2$$$. Then $$$1 \cdot 1 + 2 \cdot 1$$$ equals $$$n=3$$$.In the second test case of the example, one of the possible answers is $$$x=2, k=2$$$. Then $$$1 \cdot 2 + 2 \cdot 2$$$ equals $$$n=6$$$.In the third test case of the example, one of the possible answers is $$$x=1, k=3$$$. Then $$$1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1$$$ equals $$$n=7$$$.In the fourth test case of the example, one of the possible answers is $$$x=7, k=2$$$. Then $$$1 \cdot 7 + 2 \cdot 7$$$ equals $$$n=21$$$.In the fifth test case of the example, one of the possible answers is $$$x=4, k=3$$$. Then $$$1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4$$$ equals $$$n=28$$$.

import scala.io.StdIn

object SolutionA extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val n = StdIn.readInt();
    if (n == 1) {
      println(1)
    } else {
      var k = 2
      while (n % ((1 << k) - 1) != 0) {
        k += 1
      }
      println(n / ((1 << k) - 1))
    }
  }
}

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

  val testCount = nextInt
  for (_ <- 1 to testCount) {
    var n = nextLong
    var k = 1L
    var y = 3L
    while (n % y != 0) {
      k += 1
      y += 1 << k
    }
    out.println(n / y)
  }

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


DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.

The first line contains two integers, p and n (2 ≤ p, n ≤ 300). Then n lines follow. The i-th of them contains an integer xi (0 ≤ xi ≤ 109).

Output a single integer — the answer to the problem.

import java.io.File
import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 13.07.14.
 */
object A extends App {
  val home = true
  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 solve() = {
    val p = nextInt
    val n = nextInt
    val xs = new Array[Boolean](p)
    var printed = false
    for (i <- 0 until n if !printed) {
      //out.println(xs.toList)
      val x = nextInt
      if (xs(x % p)) {
        out.println(i + 1)
        printed = true
      } else {
        xs(x % p) = true
      }
    }
    if (!printed) {
      out.println(-1)
    }
  }

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

import java.util.StringTokenizer

object _447A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val p = next.toInt
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt % p)
  val hash = Array.fill(p)(false)

  def doit(i: Int): Int = {
    if (i == n) -1
    else if (hash(a(i))) return i + 1
    else {
      hash(a(i)) = true
      doit(i + 1)
    }
  }

  println(doit(0))
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(p, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, n).map{ _ => in.next().toInt}
  var set = Set.empty[Int]
  println(data.zipWithIndex.find{
    case(el, index) => val res = set.contains(el % p)
      set += (el % p)
      res
  }.map(_._2 + 1).getOrElse(-1))
}

import java.util.Scanner

/**
 * Created by lurker on 2014. 7. 16..
 */
object A extends App {
  def process(p:Long, values:Seq[Long] ):Integer = {
    val mark = collection.mutable.Set[Long]()
    var i = 0
    for(v <- values) {
      i += 1
      val h = v % p

      if(mark.contains(h)) {
        return i
      }
      mark += h
    }
    -1
  }

  val sc = new Scanner(System.in)
  val p = sc.nextLong()
  val n = sc.nextInt()
  val values = for(i <- (1 to n)) yield {sc.nextLong()}
  //println(process(10, Seq(0,21,53,41,53)))
  println(process(p, values.toSeq))
}

object A447 {

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

  def main(args: Array[String]): Unit = {
    val Array(p, n) = readInts(2)
    val arr = Array.fill(p)(false)
    for(i <- 1 to n) {
      val Array(xi) = readInts(1)
      if(arr(xi%p)) {
        println(i)
        return
      } else {
        arr(xi%p) = true
      }
    }
    println("-1")
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

 object Hash extends App{

  	def resolve(): Unit = {
		def hash(x: Int, p: Int) = x % p
		var map = Map[Int, Int]()

		val lines = io.Source.stdin.getLines.toIndexedSeq
		val (p, n) = {
			val tokens = lines(0).split(" ")
			(tokens(0).toInt, tokens(1).toInt)
		}

		var index = 1
		for {e <- lines.tail} {
			val bucket = hash(e.toInt, p)
			if (map.get(bucket).isDefined) {
				print(index)
				return
			} else {
				map = map + (bucket -> e.toInt)
				index += 1
			}
		}
		print(-1)
  	}

	resolve()
  }


Two integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing.Strictly increasing sequence is a sequence of integers $$$[x_1 < x_2 < \dots < x_k]$$$. And strictly decreasing sequence is a sequence of integers $$$[y_1 > y_2 > \dots > y_l]$$$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.They were merged into one sequence $$$a$$$. After that sequence $$$a$$$ got shuffled. For example, some of the possible resulting sequences $$$a$$$ for an increasing sequence $$$[1, 3, 4]$$$ and a decreasing sequence $$$[10, 4, 2]$$$ are sequences $$$[1, 2, 3, 4, 4, 10]$$$ or $$$[4, 2, 1, 10, 4, 3]$$$.This shuffled sequence $$$a$$$ is given in the input.Your task is to find any two suitable initial sequences. One of them should be strictly increasing and the other one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print "NO".

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print "NO" in the first line. Otherwise print "YES" in the first line and any two suitable sequences. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing. In the second line print $$$n_i$$$ — the number of elements in the strictly increasing sequence. $$$n_i$$$ can be zero, in this case the increasing sequence is empty. In the third line print $$$n_i$$$ integers $$$inc_1, inc_2, \dots, inc_{n_i}$$$ in the increasing order of its values ($$$inc_1 < inc_2 < \dots < inc_{n_i}$$$) — the strictly increasing sequence itself. You can keep this line empty if $$$n_i = 0$$$ (or just print the empty line). In the fourth line print $$$n_d$$$ — the number of elements in the strictly decreasing sequence. $$$n_d$$$ can be zero, in this case the decreasing sequence is empty. In the fifth line print $$$n_d$$$ integers $$$dec_1, dec_2, \dots, dec_{n_d}$$$ in the decreasing order of its values ($$$dec_1 > dec_2 > \dots > dec_{n_d}$$$) — the strictly decreasing sequence itself. You can keep this line empty if $$$n_d = 0$$$ (or just print the empty line). $$$n_i + n_d$$$ should be equal to $$$n$$$ and the union of printed sequences should be a permutation of the given sequence (in case of "YES" answer).

object C1114MixedSeq extends App {
  import scala.io.StdIn.{readLine, readInt}
  val n = readInt
  val arr1 = readLine.split(' ').map(_.toInt).groupBy(identity).mapValues(_.length)
  val arr2 = arr1.filter(_._2 == 2)
  val s1 = arr1.keys.toList.sorted
  val s2 = arr2.keys.toList.sorted.reverse
  if(s1.length + s2.length != n) {
    println("NO")
  } else {
    println("YES")
    println(s1.length)
    println(s1.mkString(" "))
    println(s2.length)
    println(s2.mkString(" "))
  }

}

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

  override def apply(io: IO): io.type = {
    val nums = io.read[Seq[Int]]

    val freqCount = nums.groupBy(identity).mapValues(_.size)

    val ans = if(freqCount.forall(_._2 <= 2)) {
      val increasing, decreasing = mutable.ArrayBuffer.empty[Int]
       freqCount foreach {
         case (i, 1) => decreasing += i
         case (i, _) =>
           increasing += i
           decreasing += i
       }

      Seq(
        "YES",
        increasing.length,
        increasing.sorted.mkString(" "),
        decreasing.length,
        decreasing.sorted(desc[Int]).mkString(" ")
      ).mkString("\n")
    } else {
      "NO"
    }

    io.write(ans)
  }

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

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

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

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

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

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

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

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

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

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

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