The city where Mocha lives in is called Zhijiang. There are $$$n+1$$$ villages and $$$2n-1$$$ directed roads in this city. There are two kinds of roads:  $$$n-1$$$ roads are from village $$$i$$$ to village $$$i+1$$$, for all $$$1\leq i \leq n-1$$$.  $$$n$$$ roads can be described by a sequence $$$a_1,\ldots,a_n$$$. If $$$a_i=0$$$, the $$$i$$$-th of these roads goes from village $$$i$$$ to village $$$n+1$$$, otherwise it goes from village $$$n+1$$$ to village $$$i$$$, for all $$$1\leq i\leq n$$$. Mocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village exactly once. They can start and finish at any villages. Can you help them to draw up a plan?

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^4$$$) — indicates that the number of villages is $$$n+1$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$). If $$$a_i=0$$$, it means that there is a road from village $$$i$$$ to village $$$n+1$$$. If $$$a_i=1$$$, it means that there is a road from village $$$n+1$$$ to village $$$i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case, print a line with $$$n+1$$$ integers, where the $$$i$$$-th number is the $$$i$$$-th village they will go through. If the answer doesn't exist, print $$$-1$$$. If there are multiple correct answers, you can print any one of them.

NoteIn the first test case, the city looks like the following graph:So all possible answers are $$$(1 \to 4 \to 2 \to 3)$$$, $$$(1 \to 2 \to 3 \to 4)$$$.In the second test case, the city looks like the following graph:So all possible answers are $$$(4 \to 1 \to 2 \to 3)$$$, $$$(1 \to 2 \to 3 \to 4)$$$, $$$(3 \to 4 \to 1 \to 2)$$$, $$$(2 \to 3 \to 4 \to 1)$$$.

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

object Solution {
  def solve(n: Int, points: Array[Int]): Seq[Int] = {
    def outgoing(pos: Int): Boolean = points(pos - 1) == 0

    // if there is n+1 -> 1 then:
    if (!outgoing(1)) {
      //   n+1 -> 1 -> 2 -> ... -> n
      (n + 1) +: (1 to n)
    // otherwise it starts with 1 since you can't get into 1
    } else if (outgoing(n)) {
      // 1 -> 2 -> 3 ... -> n -> n+1
      (1 to n) :+ (n+1)
    } else {
      // 1 -> n+1 -> 2 -> ...
      // 1 -> 2 -> ... -> i -> n+1 -> i+1 -> ... -> n
      val posOpt = (1 until n).find(pos => outgoing(pos) && !outgoing(pos + 1))
      posOpt match {
        case Some(pos) => ((1 to pos) :+ (n + 1)) ++ ((pos + 1) to n)
        case None => Seq(-1)
      }
    }
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    val n = input.nextInt()
    val points = (1 to n).map(_ => input.nextInt()).toArray
    output.println(solve(n, points).mkString(" "))
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}

import java.io._
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new BufferedReader(new java.io.InputStreamReader(System.in))
    val writer =  new PrintWriter(System.out)
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readArrayInt()
        if (a(0) == 1) {
            writer.print(s"${n + 1} ")
            writer.print(Range(1,n + 1).mkString(" "))
        } else if (a(n - 1) == 0) {
            writer.print(Range(1,n + 1).mkString(" "))
            writer.print(s" ${n + 1}")
        } else {
            breakable{
                for (i <- 0 until n - 1) {
                    if (a(i) == 0 && a(i + 1) == 1) {
                        writer.print(Range(1, i + 2).mkString(" "))
                        writer.print(s" ${n + 1} ")
                        writer.print(Range(i + 2, n + 1).mkString(" "))
                        break()
                    }
                }
                writer.print(-1)
            }
        }

        writer.println()
    }

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

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

object Solution {
  def solve(n: Int, points: Array[Int]): String = {
    def outgoing(pos: Int): Boolean = points(pos - 1) == 0

    // if there is n+1 -> 1 then:
    if (!outgoing(1)) {
      //   n+1 -> 1 -> 2 -> ... -> n
      ((n + 1) +: (1 to n)).mkString(" ")
    // otherwise it starts with 1 since you can't get into 1
    } else if (outgoing(n)) {
      // 1 -> 2 -> 3 ... -> n -> n+1
      ((1 to n) :+ (n+1)).mkString(" ")
    } else {
      // 1 -> 2 -> ... -> i -> n+1 -> i+1 -> ... -> n
      val posOpt = (1 until n).find(pos => outgoing(pos) && !outgoing(pos + 1))
      posOpt match {
        case Some(pos) => ((1 to pos) :+ (n + 1) +: ((pos + 1) to n)).mkString(" ")
        case None => "-1"
      }
    }
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    val n = input.nextInt()
    val points = (1 to n).map(_ => input.nextInt()).toArray
    output.println(solve(n, points))
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}


After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if n = 3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of digits in the cards Sherlock and Moriarty are going to use. The second line contains n digits — Sherlock's credit card number. The third line contains n digits — Moriarty's credit card number.

First print the minimum possible number of flicks Moriarty will get. Then print the maximum possible number of flicks that Sherlock can get from Moriarty.

NoteFirst sample is elaborated in the problem statement. In the second sample, there is no way Moriarty can avoid getting two flicks.

//package solutions

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

import scala.collection.mutable

/**
  * @author traff
  */

object SolTaskB extends App {
  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new Scanner(System.in), out)

    out.close()
  }

  def run(s: Scanner, out: PrintWriter): Unit = {
    val n = s.nextLine().toInt

    val a = s.nextLine().map(_.toString.toInt)
    val b = s.nextLine().map(_.toString.toInt)

    var res = 0

    var set = new mutable.HashMap[Int, Int]()

    for (i <- 0 until n) {
      set.put(b(i), set.getOrElse(b(i), 0) + 1)
    }

    for (i <- 0 until n) {
      var min = Integer.MAX_VALUE

      set.foreach { case (x, c) => if (x >= a(i) && x < min && c > 0) {
        min = x
      }
      }

      if (min < Integer.MAX_VALUE) {
        set.put(min, set.getOrElse(min, 0) - 1)
      } else {
        res += 1
        min = set.filter { case (x, c) => c > 0 }.keySet.min
        set.put(min, set.getOrElse(min, 0) - 1)
      }
    }

    out.println(res)

    res = 0

    set = new mutable.HashMap[Int, Int]()

    for (i <- 0 until n) {
      set.put(b(i), set.getOrElse(b(i), 0) + 1)
    }

    for (i <- 0 until n) {
      var min = Integer.MAX_VALUE

      set.foreach { case (x, c) => if (x > a(i) && x < min && c > 0) {
        min = x
      }
      }

      if (min < Integer.MAX_VALUE) {
        set.put(min, set.getOrElse(min, 0) - 1)
        res += 1
      } else {
        min = set.filter { case (x, c) => c > 0 }.keySet.min
        set.put(min, set.getOrElse(min, 0) - 1)
      }
    }

    out.println(res)
  }
}


On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v1, v2, v3 such that the angle  (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a. In other words, the value  should be minimum possible.If there are many optimal solutions, Mister B should be satisfied with any of them.

First and only line contains two space-separated integers n and a (3 ≤ n ≤ 105, 1 ≤ a ≤ 180) — the number of vertices in the polygon and the needed angle, in degrees.

Print three space-separated integers: the vertices v1, v2, v3, which form . If there are multiple optimal solutions, print any of them. The vertices are numbered from 1 to n in clockwise order.

NoteIn first sample test vertices of regular triangle can create only angle of 60 degrees, that's why every possible angle is correct.Vertices of square can create 45 or 90 degrees angles only. That's why in second sample test the angle of 45 degrees was chosen, since |45 - 67| < |90 - 67|. Other correct answers are: "3 1 2", "3 2 4", "4 2 3", "4 3 1", "1 3 4", "1 4 2", "2 4 1", "4 1 3", "3 1 4", "3 4 2", "2 4 3", "2 3 1", "1 3 2", "1 2 4", "4 2 1".In third sample test, on the contrary, the angle of 90 degrees was chosen, since |90 - 68| < |45 - 68|. Other correct answers are: "2 1 4", "3 2 1", "1 2 3", "4 3 2", "2 3 4", "1 4 3", "3 4 1".

import scala.io.Source

object P421B {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    // n: the number of vertices in the polygon
    // a: the needed angle, in degrees

    //    val Array(n, a) = Source.stdin.getLines().next.split(" ", 2).map(_.toInt)
    val n = sc.nextInt
    val a = sc.nextInt

    /** Output:
      * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.
      * If there are multiple optimal solutions, print any of them.
      * The vertices are numbered from 1 to n in clockwise order.
      */

    /** One of the figures is regular convex n-gon (regular convex polygon with n sides).
      * Mister B must find three distinct vertices v1, v2, v3 such that
      * the angle  (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.
      * In other words, the value  should be minimum possible.
      */

    val minAngle = 180.0 / n
    val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))
    print(Seq(2, 1, 2 + selectd).mkString(" "))
  }
}

import scala.io.Source

object P421B {
  def main(args: Array[String]): Unit = {
    val Array(n, a) = Source.stdin.getLines().next.split(" ", 2).map(_.toInt)
    assume(3 <= n)
    assume(n <= 100000)
    assume(1 <= a)
    assume(a <= 180)

    // n: the number of vertices in the polygon
    // a: the needed angle, in degrees

    /** Output:
      * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.
      * If there are multiple optimal solutions, print any of them.
      * The vertices are numbered from 1 to n in clockwise order.
      */

    /** One of the figures is regular convex n-gon (regular convex polygon with n sides).
      * Mister B must find three distinct vertices v1, v2, v3 such that
      * the angle  (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.
      * In other words, the value  should be minimum possible.
      */

    val interiorAngle = (n - 2) * 180.0 / n
    val minAngle = interiorAngle / (n - 2)
    val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))
    print(Seq(2, 1, 2 + selectd).mkString(" "))
  }
}

import scala.io.Source

object P421B {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    // n: the number of vertices in the polygon
    // a: the needed angle, in degrees

    //    val Array(n, a) = Source.stdin.getLines().next.split(" ", 2).map(_.toInt)
    val n = sc.nextInt
    val a = sc.nextInt

    /** Output:
      * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.
      * If there are multiple optimal solutions, print any of them.
      * The vertices are numbered from 1 to n in clockwise order.
      */

    /** One of the figures is regular convex n-gon (regular convex polygon with n sides).
      * Mister B must find three distinct vertices v1, v2, v3 such that
      * the angle  (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.
      * In other words, the value  should be minimum possible.
      */

    val interiorAngle = (n - 2) * 180.0 / n
    val minAngle = interiorAngle / (n - 2)
    val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))
    print(Seq(2, 1, 2 + selectd).mkString(" "))
  }
}

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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

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

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

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

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

    override def toString = s"MultiHashSet($map)"
  }

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

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

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

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

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

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

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = nextDouble
    val inner = (180.toDouble * (n - 2.toDouble)) / n.toDouble
    var min = inner
    var number = 3
    val outer = 360.toDouble / n
    for (i <- 4 to n) {
      val next = inner - ((i.toDouble - 3.toDouble) * outer / 2.toDouble)
      if (Math.abs(a - min) > Math.abs(a - next)) {
        min = next
        number = i
      }
    }
    out.println(s"1 2 $number")

    return 0
  }
}

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

  case class Point(id: Int, x: Double, y: Double)

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    import Math._

    val n, a = read[Int]

    val largest = (180.0 * (n - 2))/n

    case class Angle(v1: Point, v2: Point, v3: Point) {
      val value: Double = {
        val d = toDegrees(
          atan2(v3.x - v2.x, v3.y - v2.y) -
          atan2(v1.x - v2.x, v1.y - v2.y)
        ).abs
        if (d > largest + 1e-5) 360 - d else d
      }

      val score: Double = (a - value).abs

      override def toString = s"${v1.id} ${v2.id} ${v3.id}"
    }

    val v = IndexedSeq.tabulate(n) {i =>
      val theta = 2*i*PI/n
      Point(i + 1, sin(theta), cos(theta))
    }

    val triangles = for {
      i <- 2 until n
      Seq(v1, v2, v3) <- Seq(v(0), v(1), v(i)).permutations
    } yield Angle(v1, v2, v3)

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

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

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

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

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

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

  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 writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import scala.io.Source

object P421B {
  def main(args: Array[String]): Unit = {
    val Array(n, a) = Source.stdin.getLines().next.split(" ", 2).map(_.toInt)
    assume(3 <= n)
    assume(n <= 100000)
    assume(1 <= a)
    assume(a <= 180)

    // n: the number of vertices in the polygon
    // a: the needed angle, in degrees

    /** Output:
      * Print three space-separated integers: the vertices v1, v2, v3, which form Angle v1v2v3.
      * If there are multiple optimal solutions, print any of them.
      * The vertices are numbered from 1 to n in clockwise order.
      */

    /** One of the figures is regular convex n-gon (regular convex polygon with n sides).
      * Mister B must find three distinct vertices v1, v2, v3 such that
      * the angle  (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a.
      * In other words, the value  should be minimum possible.
      */

    val interiorAngle = (n - 2) * 180.0 / n
    val minAngle = interiorAngle / (n - 2)
    val selectd = (1 to n - 2).minBy(i => math.abs(a - i * minAngle))
    print(Seq(1, 2, 2 + selectd).mkString(" "))
  }
}

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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

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

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

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

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

    override def toString = s"MultiHashSet($map)"
  }

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

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

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

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

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

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

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = nextDouble
    val inner = (180.toDouble * (n - 2.toDouble)) / n.toDouble
    var min = inner
    var number = 3
    val outer = 360.toDouble / n
    for (i <- 4 to n) {
      val next = inner - ((i.toDouble - 3.toDouble) * outer / 2.toDouble)
      println(next)
      if (Math.abs(a - min) > Math.abs(a - next)) {
        min = next
        number = i
      }
    }
    out.println(s"1 2 $number")

    return 0
  }
}


This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury guessed some array $$$a$$$ consisting of $$$6$$$ integers. There are $$$6$$$ special numbers — $$$4$$$, $$$8$$$, $$$15$$$, $$$16$$$, $$$23$$$, $$$42$$$ — and each of these numbers occurs in $$$a$$$ exactly once (so, $$$a$$$ is some permutation of these numbers).You don't know anything about their order, but you are allowed to ask up to $$$4$$$ queries. In each query, you may choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le 6$$$, $$$i$$$ and $$$j$$$ are not necessarily distinct), and you will get the value of $$$a_i \cdot a_j$$$ in return.Can you guess the array $$$a$$$?The array $$$a$$$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries.

NoteIf you want to submit a hack for this problem, your test should contain exactly six space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_6$$$. Each of $$$6$$$ special numbers should occur exactly once in the test. The test should be ended with a line break character.


You are given a positive integer $$$n$$$. You have to find $$$4$$$ positive integers $$$a, b, c, d$$$ such that  $$$a + b + c + d = n$$$, and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.If there are several possible answers you can output any of them. It is possible to show that the answer always exists.In this problem $$$\gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$, and $$$\operatorname{lcm}(c, d)$$$ denotes the least common multiple of $$$c$$$ and $$$d$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with integer $$$n$$$ ($$$4 \le n \le 10^9$$$) — the sum of $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$.

For each test case output $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ such that $$$a + b + c + d = n$$$ and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.

import scala.io.StdIn.readLine

object Solution {

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

  def solve(n: Int) = {
    if (n == 5) println("2 1 1 1")
    else if (n % 4 == 0) println(s"${n / 4} ${n / 4} ${n / 4} ${n / 4}")
    else if (n % 2 == 0) println(s"${n / 2 - 2} ${n / 2} 1 1")
    else println(s"${n - 5} 2 2 1")
  }

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

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

import scala.io.StdIn

object Task1 extends App {

  def getNextNum: Int = StdIn.readLine().toInt

  val dataSize = getNextNum

  for (_ <- 0 until dataSize) {
    val n = getNextNum
    println(s"${n - 3} 1 1 1")
  }

}

import scala.io.StdIn.readLine

object Solution {

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

  def solve(n: Int) = {
    if (n % 4 == 0) println(s"${n / 4} ${n / 4} ${n / 4} ${n / 4}")
    else if (n % 2 == 0) println(s"${n / 2 - 2} ${n / 2} 1 1")
    else println(s"${n - 5} 2 2 1")
  }

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

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


Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.Andryusha wants to use as little different colors as possible. Help him to choose the colors!

The first line contains single integer n (3 ≤ n ≤ 2·105) — the number of squares in the park. Each of the next (n - 1) lines contains two integers x and y (1 ≤ x, y ≤ n) — the indices of two squares directly connected by a path. It is guaranteed that any square is reachable from any other using the paths.

In the first line print single integer k — the minimum number of colors Andryusha has to use. In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k.

NoteIn the first sample the park consists of three squares: 1 → 3 → 2. Thus, the balloon colors have to be distinct.    Illustration for the first sample. In the second example there are following triples of consequently connected squares:   1 → 3 → 2  1 → 3 → 4  1 → 3 → 5  2 → 3 → 4  2 → 3 → 5  4 → 3 → 5  We can see that each pair of squares is encountered in some triple, so all colors have to be distinct.    Illustration for the second sample. In the third example there are following triples:   1 → 2 → 3  2 → 3 → 4  3 → 4 → 5  We can see that one or two colors is not enough, but there is an answer that uses three colors only.    Illustration for the third sample.

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

import scala.collection.mutable._

object Solution {

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

  def main(args: Array[String]) {
    val Array(n) = readInts(1)

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

    (0 to n - 2).foreach { _ =>
      val Array(x, y) = readInts(2)
      adj(x - 1).append(y - 1)
      adj(y - 1).append(x - 1)
    }

    val q = mutable.Queue[Int]()
    val pre = Array.fill[Int](n)(0)
    val col = Array.fill[Int](n)(0)
    val visited = Array.fill(n)(false)

    var k = 0

    q.enqueue(0)
    pre(0) = 0
    col(0) = 1

    while (q.nonEmpty) {
      val cur = q.dequeue()
      visited(cur) = true
      k = Math.max(k, 1 + adj(cur).size)

      var cid = 1
      adj(cur).foreach { next =>
        if (!visited(next)) {
          while (pre(cur) == cid || col(cur) == cid) cid += 1
          col(next) = cid
          pre(next) = col(cur)
          cid += 1
          q.enqueue(next)
        }
      }
    }

    println(k)
    print(col(0))
    for (i <- 1 to n - 1) print(" " + col(i))
    println()

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}


This problem is interactive.We have hidden an array $$$a$$$ of $$$n$$$ pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon. This device can answer queries of the following form: in response to the positions of $$$k$$$ different elements of the array, it will return the position and value of the $$$m$$$-th among them in the ascending order.Unfortunately, the instruction for the device was lost during delivery. However, you remember $$$k$$$, but don't remember $$$m$$$. Your task is to find $$$m$$$ using queries to this device. You can ask not more than $$$n$$$ queries.Note that the array $$$a$$$ and number $$$m$$$ are fixed before the start of the interaction and don't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries, and you don't need to guess array $$$a$$$. You just have to guess $$$m$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\le k < n \le 500$$$) — the length of the array and the number of the elements in the query. It is guaranteed that number $$$m$$$ satisfies $$$1\le m \le k$$$, elements $$$a_1, a_2, \dots, a_n$$$ of the array satisfy $$$0\le a_i \le 10^9$$$, and all of them are different.

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

  val n, k = nextInt
  val ids = Array.tabulate(k + 1)(_ + 1)
  val xs = Array.ofDim[Int](k + 1)
  for (i <- 0 until k + 1) {
    val ask = ids.filterNot(_ == i + 1)
    out.println("? " + ask.mkString(" "))
    out.flush()
    val pos, x = nextInt
    xs(i) = x
  }

  val max = xs.max
  val res = xs.count(_ == max)

  out.println(s"! $res")
  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
  }
}

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

  val n, k = nextInt
  val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)
  val xs = Array.ofDim[Int](k + 1)
  for (i <- 0 until k + 1) {
    val ask = ids.view(i, i + k)
    out.println("? " + ask.mkString(" "))
    out.flush()
    val pos, x = nextInt
    xs(i) = x
  }

  val max = xs.max
  val res = xs.count(_ == max)

  out.println(s"! $res")
  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
  }
}

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

  val n, k = nextInt
  val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)
  val xs = Array.ofDim[Int](n)
  for (i <- 0 until n) {
    val ask = ids.view(i, i + k)
    out.println("? " + ask.mkString(" "))
    out.flush()
    val pos, x = nextInt
    xs(i) = x
  }

  val counts = xs.groupBy(identity).map {
    case (key, values) => key -> values.length
  }
  val max = counts.valuesIterator.max
  val countsWithMax = counts.valuesIterator.count(_ == max)
  val mode = xs.maxBy(counts)
  val x = xs.filter(x => counts(x) == mode).max
  val sorted = xs.sortBy(counts)
  val median = sorted(n / 2)
  val res = if (mode < median) xs.count(_ < mode) else k - xs.count(_ > mode)

  out.println(s"! $res")
  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
  }
}

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

  val n, k = nextInt
  val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)
  val xs = Array.ofDim[Int](n)
  for (i <- 0 until n) {
    val ask = ids.view(i, i + k)
    out.println("? " + ask.mkString(" "))
    out.flush()
    val pos, x = nextInt
    xs(i) = x
  }

  val counts = xs.groupBy(identity).map {
    case (key, values) => key -> values.length
  }
  val max = xs.maxBy(counts)
  val res = k - xs.count(_ > max)

  out.println(s"! $res")
  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
  }
}

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

  val n, k = nextInt
  val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)
  val xs = Array.ofDim[Int](n)
  for (i <- 0 until n) {
    val ask = ids.view(i, i + k)
    out.println("? " + ask.mkString(" "))
    out.flush()
    val pos, x = nextInt
    xs(i) = x
  }

  val max = xs.max
  val res = xs.count(_ == max)

  out.println(s"! $res")
  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
  }
}

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

  val n, k = nextInt
  val ids = Array.tabulate(n)(_ + 1) ++ Array.tabulate(n)(_ + 1)
  val xs = Array.ofDim[Int](n)
  for (i <- 0 until n) {
    val ask = ids.view(i, i + k)
    out.println("? " + ask.mkString(" "))
    out.flush()
    val pos, x = nextInt
    xs(i) = x
  }

  val counts = xs.groupBy(identity).map {
    case (key, values) => key -> values.length
  }
  val max = counts.valuesIterator.max
  val countsWithMax = counts.valuesIterator.count(_ == max)
  val mode = xs.maxBy(counts)
  val res = if (countsWithMax == 2) (k + 1) / 2 else k - xs.count(_ > mode)

  out.println(s"! $res")
  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
  }
}


The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:  Operation ++ increases the value of variable x by 1.  Operation -- decreases the value of variable x by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).

The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme. Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.

Print a single integer — the final value of x.

object Main {
  def main(args: Array[String]): Unit = {
    val n = readLine.toInt
    var sum = 0
    var i = 0
    while(i < n) {
      val line = readLine
      if (line.contains("+")) sum = sum + 1 else sum = sum - 1
      i = i + 1
    }
    println(sum)
  }
}

import scala.io.StdIn

object  Test {
  def main(args1: Array[String]) {
    //    val args = StdIn.readLine().split(" ")
    //    var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)

    val count = StdIn.readInt

    var ret = 0L
    for (i <- 0 until count) {
      val a = StdIn.readLine()
      if (a.contains("X")) {
        if (a.contains("++")) {
          ret += 1
        }
        else if (a.contains("--")) {
          ret -= 1
        }
      }
    }
    println(ret)
  }

}

object TwoEightTwoA {

	def main(args : Array[String]) : Unit = {
		var x=0
		var n=readInt
		for(i<-0 until n){
			var op=readLine
			op match{
				case "++X"=>x+=1
				case "X++"=>x+=1
				case "--X"=>x-=1
				case "X--"=>x-=1
			}
		}
		println(x)
	}
}

import scala.io.StdIn._

object Bits {
  def main(args: Array[String]): Unit = {
    val ins = Map("++x" -> 1, "x++" -> 1, "--x" -> -1, "x--" -> -1)
    val n = readInt()
    val instructions = for (_ <- 0 until n) yield readLine().toLowerCase()
    val result = instructions.map(ins).reduce(_ + _)
    println(result)
  }
}

object Main extends App {
  def A71 = {
    def packWord(s: String, i: Int) : String = {
      s.length > i match {
        case false => s
        case true => s"${s(0)}${s.length - 2}${s.last}"
      }
    }
    (1 to readInt).map( _ => {
      readLine
    }).map(packWord(_, 10)).foreach(println(_))
  }
  def A4 = {
    println (readInt % 2 == 0 match {
      case true => println("YES")
      case false => println("NO")
    })
  }
  def A158 = {
    val k = readLine.split(' ')(1).toInt
    val xs = readLine.split(' ').map(_.toInt)
    val treshold = xs(k-1)
    println(xs.count(x => { x >= treshold && x > 0 }))
  }
  def A282: Unit = {
    println((1 to readInt).map( _ => {
      readLine
    }).foldLeft(0)((acc: Int,i: String) => {
      i.contains('+') match {
        case true => acc + 1
        case false => acc - 1
      }
    }))
  }
  A282
}

import scala.io.StdIn

/**
  * Created by vladimir on 06.06.17.
  */
object A282 extends App {
  var initialState = 0
  val n = StdIn.readInt()
  for (_ <- 0 until n) {
    val statement = StdIn.readLine()
    if (statement.contains('+'))
      initialState += 1
    else
      initialState -= 1
  }
  println(initialState)
}

object Bitpp {
	def main(args:Array[String]) {
		var x=0;
		var n=readInt();
		var s:String="";
		while (n>0) {
			n-=1;
			s=readLine();
			if (s.equals("X++") || s.equals("++X")) {
				x+=1;
			}
			else
			{
				x-=1;
			}
		}
		println(x);
	}
}

object bit_plus_plus extends App {
  var x = 0

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

  for (i <- 1 to commandIterations) {
    val command = scala.io.StdIn.readLine()
    if (command.contains("++")) x += 1
    else if (command.contains("--")) x-=1
  }
  println(x)
}

import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine().toInt

  var result = 0

  for (_ <- 1 to n) {
    val str = StdIn.readLine()
    str match {
      case "X++" => result += 1
      case "++X" => result += 1
      case "X--" => result -= 1
      case "--X" => result -= 1
    }
  }

  println(result)
}

object CF282A {
    def main(argc: Array[String]) {
        def deal(left: Int, x: Int) : Int = {
            if (left == 0) x
            else {
                readLine match {
                    case "X++" | "++X" => deal(left - 1, x + 1)
                    case "X--" | "--X" => deal(left - 1, x - 1)
                }
            }
        }
        println(deal(readLine.toInt, 0))
    }
}

object CF0282A extends App {

  val n = readInt()

  var accomulator = 0

  (1 to n).foreach(value => {
    val str = readLine()
    if (str.contains("++")) {
      accomulator += 1
    } else if (str.contains("--")) {
      accomulator -= 1
    }
  })

  println(accomulator)

}

object HelloWorld {
  def main(args: Array[String]): Unit = {
  	var n = readInt()
  	var ans = 0
  	for(i <- 0 until n){
  		var s = readLine()
  		if (s(1) == '+'){
  				ans = ans +1
  		}else
  			ans = ans- 1
  	}
  	println(ans)
  }
}

object task282A {
  def main(args:Array[String]) {
    var rv:Int=0;
    for (l <- io.Source.stdin.getLines.toList.drop(1)) {
      l(1) match {
        case '-' => rv-=1
        case '+' => rv+=1
      }
    }
    println(rv)
  }
}

object pratise {
    def main(args : Array[String]) {
        var res = 0
        (1 to readInt).map(_ => readLine).foreach {
            case "++X" | "X++" => res+=1
            case "--X" | "X--" => res-=1
        }
        println(res)
    }
}

object cf extends App{
  val t = readInt()
  var res = 0
  for (i <- 0 to t-1) {
    val s = readLine()
    if (s(1) == '+') {
      res += 1
    }
    else {
      res -= 1
    }
  }
  println(res)
}

object BitPlusPlus extends App {

  var value = 0

  def process(s: String) = {
    if (s.contains("++")) value = value + 1
    if (s.contains("--")) value = value - 1
  }

  (1 to readInt()).map(line => process(readLine()))
  println(value)
}

import scala.io.StdIn.readLine
object Solution {
    def readLines(n: Int) = Iterator.continually(readLine).take(n).toIterable
    def converge(expressions: Iterable[String]) = expressions map (_ match {
        case "--X" | "X--" => -1
        case "++X" | "X++" => 1
    })
    def main(args: Array[String]) = {
        val n = readLine.toInt
        println(converge(readLines(n)) reduceLeft (_ + _))
    }
}

 object Main extends App {
    def A282 ={
    var acc =0
    (1 to readInt).map(_ => {
      readLine()(1) == '+' match {
        case true => acc=acc+1
        case false => acc=acc-1
      }

    })
    println(acc)

  }

 A282
}

object Solution282A extends App {

  def solution() {
    val result = 1.to(_int).map(_ => _string).foldLeft(0)((memo, str) => str match {
      case pl if pl.contains("+") => memo + 1
      case _ => memo - 1
    })
    println(result)
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

object A extends App {
  val n = readLine.toInt
  def solve(): Int = {
    val line = readLine
    if(line == null) return 0
    val res: Int =
      if(line.startsWith("++")) 1
      else if(line.startsWith("--")) -1
      else if(line.endsWith("++")) 1
      else if(line.endsWith("--")) -1
      else 0
    res + solve
  }
  println(solve)
}

// http://codeforces.com/problemset/problem/282/A

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

object BitPlusPlus {
    def main(args: Array[String]): Unit = {
        val n: Int = readInt()
        var x: Int = 0
        for(i <- 1 to n) {
            var line: String = readLine()
            if(line.contains("+")) {
                x += 1
            } else if(line.contains("-")) {
                x -= 1
            }
        }

        println(x)
    }
}

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val n = StdIn.readLine().toInt
  var res = 0
  for (i <- 1 to n) {
    res += (if (StdIn.readLine().contains("+")) 1 else -1)
  }

  println(res)
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val ans = (0 until n).map { k =>
      val op = readLine
      if (op.contains("++")) 1 else -1
    }.sum
    println(ans)
  }
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var count = 0
  Range(0, n).foreach {_ =>
    if (in.next().contains('+')) count += 1 else count -= 1}
  println(count)
}

object Main {
  def main(args: Array[String]) {
    val std = scala.io.StdIn
    val n = std.readInt()
    var result = 0
    for (i <- 0 until n) {
      std.readLine() match {
        case x if x.contains("++") =>
          result +=1
        case x if x.contains("--") =>
          result -=1
      }
    }
    println(result)
  }
}

import scala.io.StdIn

object Bit extends App {

  val n = StdIn.readInt()
  var value = 0
  for (i <- Range(0, n)) {
    value = impl(StdIn.readLine(), value)
  }
  print(value)

  def impl(in: String, value: Int): Int = {
    in match {
      case "++X" | "X++" => value + 1
      case "--X" | "X--" => value - 1
    }
  }
}

object Main {
  def main(args: Array[String]) = {
    val n = readLine.toInt
    var ans = 0

    for(i <- 1 to n)
      readLine match {
        case "X++" | "++X" => ans += 1
        case "X--" | "--X" => ans -= 1
      }

    println(ans)
  }
}

import scala.io.StdIn

object Bit extends App
{
    val numOfLines = StdIn.readInt()
    def input: Seq[String] = for (_ <- 1 to numOfLines) yield StdIn.readLine()
    def sort = input.map
    {
        case word if (word.charAt(1) == '+') =>  1
        case word if (word.charAt(1) == '-') => -1
    }
    println(sort.sum)
}

object HelloWorld {
   def main(args: Array[String]) {
      val n = readInt
      var c = 0
      for (i <- 0 until n) {
          c += (if(readLine.contains('+')) 1 else -1)
      }
      println(c)
   }
}

/**
 * Created by richard on 2015/6/8.
 */
import scala.io.StdIn
object hello {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    var c = 0
    for (i<-0 until n) {
      c += (if (StdIn.readLine().charAt(1) == '+') 1 else -1)
    }
    println(c)
  }
}

object E {

  def main (args : Array[String]) : Unit ={
    var n = readInt
    var ans = 0
    for (i <- 1 to n){
      var s = readLine
      var bol = false
      for (j <- 0 to s.length()-1){
        if (s.charAt(j)=='+' && !bol){
          ans += 1;
          bol = true
        }else if (s.charAt(j)=='-' && !bol){
          ans -= 1;
          bol = true;
        }
      }
    }
    println(ans)
  }

}

object A282 {
  @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 Array(n) = readInts(1)
    var x = 0
    for(_ <- 0 until n) {
      val input = scala.io.StdIn.readLine
      if(Array("++X", "X++").contains(input)) {
        x += 1
      } else {
        x -= 1
      }
    }
    println(x)
  }
}

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

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

  val N = sc.nextLine.toInt

  @tailrec
  def loop(acc: Int, i: Int): Int =
    if (i == N) acc
    else {
      val l = sc.nextLine
      if (l == "X++" || l == "++X") loop(acc + 1, i + 1)
      else loop(acc - 1, i + 1)
    }

  def solve: Int = loop(0, 0)

  out.println(solve)
  out.close
}

object Bitpp {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in)
		val n = scanner.nextInt
		var value = 0
		for (i <- 0 to n) {
		  val line = scanner.nextLine()
		  line match {
		    case "++X" | "X++" => value = value + 1
		    case "--X" | "X--" => value = value - 1
		    case  _ =>
		  }
		}
		println(value)
	}
}

object A {
   def READ: Array[Int] = readLine() split (" ")  map (_.toInt);
   def main(args: Array[String]) {
     var Array(n) = READ
     var r = 0;
     for (i <- 1 to n)
       r += (if (readLine().contains("++")) 1 else -1);
     println(r)
   }
}

import java.util.Scanner

object Try1 {
  def main(args: Array[String]) {
    val in = new Scanner(System.in)
    var len,x, m, k, n, j, i: Int = 0
    var a = new Array[Int](51)
    n = in.nextInt()
//    k = in.nextInt()
    x=0
    var line = in.nextLine()
    for (i <- 1 to n) {
      line = in.nextLine()
      if (line(1)=='-') x-=1
      else x+=1
    }
    println(x)
  }
}

import java.io._

object Main extends App {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  val n = reader.readLine.toInt
  val x = 0
  val arr = new Array[String](n)
  for (i <- 0 until n) arr(i) = reader.readLine()
  val plus = arr.count(_.contains("+"))
  val minus = arr.count(_.contains("-"))
  println(plus - minus)
}

object Codeforces282A extends App{

  def MainCompilation(linenumber:Int):Int={
    var ans:Int=0
    for (i <- 0 until linenumber){
      val temp:String=scala.io.StdIn.readLine
      if (temp=="++X" || temp=="X++") ans+=1
      else if (temp=="--X" || temp=="X--") ans-=1
    }
    return ans
  }
  val numberofline:Int=scala.io.StdIn.readInt
  println(MainCompilation(numberofline))

}

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

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

  def ans = (for(_ <- 1 to readInt) yield if(reader.readLine()(1) == '+') 1 else -1).sum

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

/**
 * Created by vol on 9/18/14.
 */
object A282 extends App{
  val n = readInt()

  def loop(n:Int, i:Int, acc:Int):Int= {
    if (n == i) acc
    else {
      val sentence = readLine()
      if (sentence == "X++" || sentence == "++X") loop(n, i + 1, acc + 1)
      else loop(n, i + 1, acc -1)
    }
  }

  println(loop(n, 0, 0))

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val res = (1 to n).foldLeft(0) { (acc, unused) =>
      readLine() match {
        case s: String if s.contains("+") => acc + 1
        case s: String if s.contains("-") => acc - 1
      }
    }
    println(res)
  }
}

// Codeforces 282A

object _282A extends App {
  val scanner = new java.util.Scanner(System.in)
  val n = scanner.nextInt
  val operation = Array.fill(n)(scanner.next())
  val answer =
    operation.map(op => if (op.contains("++")) 1 else -1).
      foldLeft(0)((accm, i) => accm + i)
  println(answer)
}

import scala.io.StdIn._

object BitProb extends App {
  val tItr = readInt()

  def countBits(i: Int = 0, acc: Int = 0): Int = {
    if(i == tItr) acc
    else {
      val inStr = readLine()
      if (inStr.matches("X\\+\\+") || inStr.matches("\\+\\+X")) countBits(i + 1, acc + 1)
      else if (inStr.matches("X--") || inStr.matches("--X")) countBits(i + 1, acc - 1)
      else countBits(i + 1, acc)
    }
  }

  val finalBit = countBits()

  print(finalBit)
}

object JuanDavidRobles282A {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn

    var lines : Int = StdIn.readInt()

    var command : String = ""
    var count : Int = 0

    for (i <- 0 until lines){
      command = StdIn.readLine()
      if (command contains("+")){
        count = count + 1
      } else {
        count = count - 1
      }
    }

    println(count)
  }
}

object CF173Div2A {
  def main(args: Array[String]){
    var x = 0
    val n = readLine.toInt
    (1 to n).map(_ => readLine).foreach{
      case "++X"|"X++" => x += 1
      case "--X"|"X--" => x -= 1
    }
    println(x)
  }
}

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

object BitPlusPlus {
  def main(args: Array[String]) {
    val n = readInt
    val ops = for {
      i <- 1 to n
      line = readLine
      op = if (line.contains("+")) 1 else -1
    } yield op
    println(ops.sum)
  }
}

object test extends App
{
    var ans =0
    for(i <- 1 to readInt)
        ans += (if(readLine.contains("+")) 1 else -1)
    print (ans)
}

object codeforces {
  def main(args: Array[String]): Unit = {
    val n: Int = scala.io.StdIn.readLine().toInt
    var x: Int = 0
    for (_ <- 0 until n){
      val line: String = scala.io.StdIn.readLine()
      if ((line.head == '+' && line(1) == '+') || (line(1) == '+' && line(2) == '+')){
        x+=1
      }else{
        if ((line.head == '-' && line(1) == '-') || (line(1) == '-' && line(2) == '-')){
          x-=1
        }
      }
    }
    println(x)
  }
}

import scala.io.StdIn._

object Solution {

	var n = readInt
	var lns = Array.fill[String](n)(null)
	for(i <- 0 until n) {
		lns(i) = readLine
	}

	def main(args:Array[String]):Unit = {
		var x = 0
		var op = ""
		for(i <- 0 until n) {
			op = if(lns(i)(0) == 'X') lns(i)(1).toString + lns(i)(2).toString
				 else lns(i)(0).toString + lns(i)(1).toString
			if(op == "++") x += 1
			else x -= 1
		}
		println(x)
	}

}

object main extends App{
    val s = readInt
    var cnt = 0
    for(i <- 0 until s){
            if(readLine.contains('+')) cnt+=1 else cnt-=1
    }
    println(cnt)
}

object main extends App{
    val s = readInt
    var cnt = 0
    (1 to s).map(_ => readLine).foreach{
        case "++X" | "X++" => cnt+=1
        case "--X" | "X--" => cnt-=1
    }
    println(cnt)
}

object A00282 extends App {
    val n = Console.readInt();
    var x = 0
    for (i <- 1 to n) {
      val str = Console.readLine();
      if (str.contains("++")) {
        x = x + 1
      } else if (str.contains("--")) {
        x = x - 1
      }
    }
    println(x)
}

object CF282A {
    def main(argc: Array[String]) {
        def deal(left: Int, x: Int) {
            if (left == 0) x
            else {
                readLine match {
                    case "X++" | "++X" => deal(left - 1, x + 1)
                    case "X--" | "--X" => deal(left - 1, x - 1)
                }
            }
        }
        println(deal(readLine.toInt, 0))
    }
}

object Main extends App {
    def A258 ={
    var acc =0
    (1 to readInt).map(_ => {
      readLine()(1) == '+' match {
        case true => acc=acc+1
        case false => acc=acc-1
      }

    })
    println(acc)

  }

}

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

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

  val N = sc.nextLine.toInt

  @tailrec
  def loop(acc: Int, i: Int): Int =
    if (i == N) acc
    else {
      val l = sc.nextLine
      if (l == "X++" || i == "++X") loop(acc + 1, i + 1)
      else loop(acc - 1, i + 1)
    }

  def solve: Int = loop(0, 0)

  out.println(solve)
  out.close
}

import scala.io.StdIn._

object Main extends App {
  val tItr = readInt()

  def countBits(i: Int = 0, acc: Int = 0): Int = {
    if(i == tItr) acc
    else {
      val inStr = readLine()
      if (inStr.contains("++")) countBits(i + 1, acc + 1)
      else countBits(i + 1, acc - 1)
    }
  }

  val finalBit = countBits().toBinaryString

  print(finalBit)
}

import scala.io.StdIn._

object BitProb extends App {
  val tItr = readInt()

  def countBits(i: Int = 0, acc: Int = 0): Int = {
    if(i == tItr) acc
    else {
      val inStr = readLine()
      if (inStr.matches("X\\+\\+") || inStr.matches("\\+\\+X")) countBits(i + 1, acc | 1)
      else if (inStr.matches("X--") || inStr.matches("--X")) countBits(i + 1, acc & 0)
      else countBits(i + 1, acc)
    }
  }

  val finalBit = countBits()

  print(finalBit)
}

import scala.io.StdIn._

object BitProb extends App {
  val tItr = readInt()

  def countBits(i: Int = 0, acc: Int = 0): Int = {
    if(i == tItr) acc
    else {
      val inStr = readLine()
      if (inStr.matches("X\\+\\+") || inStr.matches("\\+\\+X")) countBits(i + 1, acc + 1)
      else if (inStr.matches("X--") || inStr.matches("--X")) countBits(i + 1, acc - 1)
      else countBits(i + 1, acc)
    }
  }

  val finalBit = countBits().toBinaryString

  print(finalBit)
}

object main extends App{
    val s = readLine().toInt
    var cnt = 1
    for(i <- 1 to s){
        val t = readLine
        if(t.last =="+" || t.head =="+") cnt+=1
        if(t.last =="-" || t.head =="-") cnt-=1
    }
    println(cnt)
}

object main extends App{
    val s = readLine().toInt
    var cnt = 0
    for(i <- 1 to s){
        val t = readLine
        if(t.last =="+" || t.head =="+") cnt+=1
        if(t.last =="-" || t.head =="-") cnt-=1
    }
    println(cnt)
}


You have a card deck of $$$n$$$ cards, numbered from top to bottom, i. e. the top card has index $$$1$$$ and bottom card — index $$$n$$$. Each card has its color: the $$$i$$$-th card has color $$$a_i$$$.You should process $$$q$$$ queries. The $$$j$$$-th query is described by integer $$$t_j$$$. For each query you should:   find the highest card in the deck with color $$$t_j$$$, i. e. the card with minimum index;  print the position of the card you found;  take the card and place it on top of the deck.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 3 \cdot 10^5$$$; $$$1 \le q \le 3 \cdot 10^5$$$) — the number of cards in the deck and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — the colors of cards. The third line contains $$$q$$$ integers $$$t_1, t_2, \dots, t_q$$$ ($$$1 \le t_j \le 50$$$) — the query colors. It's guaranteed that queries ask only colors that are present in the deck.

Print $$$q$$$ integers — the answers for each query.

NoteDescription of the sample:   the deck is $$$[2, 1, 1, 4, \underline{3}, 3, 1]$$$ and the first card with color $$$t_1 = 3$$$ has position $$$5$$$;  the deck is $$$[3, \underline{2}, 1, 1, 4, 3, 1]$$$ and the first card with color $$$t_2 = 2$$$ has position $$$2$$$;  the deck is $$$[2, 3, \underline{1}, 1, 4, 3, 1]$$$ and the first card with color $$$t_3 = 1$$$ has position $$$3$$$;  the deck is $$$[\underline{1}, 2, 3, 1, 4, 3, 1]$$$ and the first card with color $$$t_4 = 1$$$ has position $$$1$$$;  the deck is $$$[1, 2, 3, 1, \underline{4}, 3, 1]$$$ and the first card with color $$$t_5 = 4$$$ has position $$$5$$$.

object P1511C {

  import java.io._

  val out: OutputPrinter = new StringOutputPrinter(1024)
  //val out: OutputPrinter = new OutputPrinter()
  //val out: OutputPrinter = new BufferedOutputPrinter()
  val input = new InputReader(new InputStreamReader(System.in))
  //val input = new InputReader(new FileReader("input.txt"))
  //val input = new InputReader(new StringReader("7 5\n2 1 1 4 3 3 1\n3 2 1 1 4"))
  //  val input = new InputReader(new StringReader(
  //    """3 3
  //      1 2 3
  //      1 3 1
  //    """))

  def main(args: Array[String]): Unit = {
    //val startTime = System.currentTimeMillis()

    val executor = new Solution3
    executor.solve()

    out.flush()
    //val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    import java.util

    def solve(): Unit = {
      val deckSize, qs = input.nextInt
      val deck = new util.LinkedList[Byte]()
      input.forBytes(deckSize) { (_, color) => deck.add(color) }
      input.forBytes(qs) { (_, color) =>
        val index = deck.indexOf(color)
        out.print(index + 1)
        out.print(' ')
        deck.remove(index)
        deck.addFirst(color)
      }
    }
  }

  class Solution2 {

    def solve(): Unit = {
      val deckSize, qs = input.nextInt

      val colorPlaces = Array.fill[Int](51)(99)
      input.forBytes(deckSize) { (place, color) =>
        if (colorPlaces(color) == 99) {
          colorPlaces(color) = place
        }
      }

      input.forBytes(qs) { (_, color) =>
        val place = colorPlaces(color)
        out.print(place + 1)
        out.print(' ')
        for (clr <- colorPlaces.indices) {
          val plc = colorPlaces(clr)
          if (plc < place) {
            colorPlaces(clr) = plc + 1
          }
        }
        colorPlaces(color) = 0
      }
    }
  }

  class Solution3 {

    private val head: MyNode = new MyNode(-1)
    private var last: MyNode = head

    private def add(color: Byte): Unit = {
      last.next = new MyNode(color)
      last = last.next
    }

    private def findIndexAndMoveToTop(color: Byte) = {
      var index = 1
      var parent = head
      var current = head.next
      while (current.value != color) {
        parent = current
        current = parent.next
        index += 1
      }
      if (current == last) {
        last = parent
      }
      parent.next = current.next
      current.next = head.next
      head.next = current
      index
    }

    def solve(): Unit = {
      val deckSize, qs = input.nextInt
      input.forBytes(deckSize) { (_, color) => add(color) }
      input.forBytes(qs) { (_, color) =>
        val place = findIndexAndMoveToTop(color)
        out.print(place)
        out.print(' ')
      }
    }
  }

  class MyNode(val value: Byte) {
    var next: MyNode = _
  }

  class InputReader(reader: Reader) {

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

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class DirectOutputPrinter extends OutputPrinter {

    override def print(c: Char): Unit = System.out.print(c)

    override def print(i: Int): Unit = System.out.print(i)

    override def print(s: String): Unit = System.out.print(s)

    override def endl(): Unit = System.out.println()

    override def flush(): Unit = System.out.flush()
  }

  class StringOutputPrinter(capacity: Int) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = println(buffer.result())
  }

  class BufferedOutputPrinter extends OutputPrinter {
    private val buffer = new PrintWriter(System.out)

    override def print(c: Char): Unit = buffer.print(c)

    override def print(i: Int): Unit = buffer.print(i)

    override def print(s: String): Unit = buffer.print(s)

    override def endl(): Unit = buffer.println()

    override def flush(): Unit = buffer.flush()
  }

}

object P1511C {

  import java.io._

  val out = new StringBuilder(1024)
  val input = new InputReader(new InputStreamReader(System.in))

  def main(args: Array[String]): Unit = {
    val executor = new Solution3
    executor.solve()
    println(out.result())
  }

  class Solution3 {

    private val head: MyNode = new MyNode(-1)
    private var last: MyNode = head

    private def add(color: Byte): Unit = {
      last.next = new MyNode(color)
      last = last.next
    }

    private def findIndexAndMoveToTop(color: Byte) = {
      var index = 1
      var parent = head
      var current = head.next
      while (current.value != color) {
        parent = current
        current = parent.next
        index += 1
      }
      if (current == last) {
        last = parent
      }
      parent.next = current.next
      current.next = head.next
      head.next = current
      index
    }

    def solve(): Unit = {
      val deckSize, qs = input.nextInt
      input.forBytes(deckSize) { (_, color) => add(color) }
      input.forBytes(qs) { (_, color) =>
        val place = findIndexAndMoveToTop(color)
        out.append(place)
        out.append(' ')
      }
    }
  }

  class MyNode(val value: Byte) {
    var next: MyNode = _
  }

  class InputReader(reader: Reader) {

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

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

}

import java.io.PrintWriter

object P1511C {

  import java.io.{BufferedReader, StringReader}

  def main(args: Array[String]): Unit = {
    import scala.io.Source
    val input = Source.stdin.bufferedReader()
    //val input = Source.fromFile("input.txt").bufferedReader()
    //val input = new BufferedReader(new StringReader("7 5\n2 1 1 4 3 3 1\n3 2 1 1 4"))
    //    val input = new BufferedReader(new StringReader(
    //      """3 3
    //      1 2 3
    //      1 3 1
    //    """))
    val output = new PrintWriter(System.out)
    val executor = new Solution2(input, output)
    val startTime = System.currentTimeMillis()
    executor.solve()
    output.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1(input: BufferedReader, output: PrintWriter) {

    import java.util
    import java.util.StringTokenizer

    def solve(): Unit = {
      val prms = new StringTokenizer(input.readLine())
      val deckSize = prms.nextToken().toInt
      val qs = prms.nextToken().toInt
      val deckParser = new StringTokenizer(input.readLine())
      val deck = new util.LinkedList[Byte]()
      for (_ <- 0 until deckSize) {
        deck.add(deckParser.nextToken().toByte)
      }
      val qParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until qs) {
        val color = qParser.nextToken().toByte
        val index = deck.indexOf(color)
        output.print(index + 1)
        output.print(' ')
        deck.remove(index)
        deck.addFirst(color)
      }
      output.println()
    }
  }

  class Solution2(input: BufferedReader, output: PrintWriter) {

    import java.util.StringTokenizer

    def solve(): Unit = {
      val prms = new StringTokenizer(input.readLine())
      val deckSize, qs = prms.nextToken.toInt

      val deckParser = new StringTokenizer(input.readLine())
      val colorPlaces = Array.fill[Int](51)(99)
      for (place <- 0 until deckSize) {
        val color = deckParser.nextToken.toInt
        if (colorPlaces(color) == 99) {
          colorPlaces(color) = place
        }
      }

      val qParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until qs) {
        val color = qParser.nextToken.toInt
        val place = colorPlaces(color)
        output.print(place + 1)
        output.print(' ')
        for (clr <- colorPlaces.indices) {
          val plc = colorPlaces(clr)
          if (plc < place) {
            colorPlaces(clr) = plc + 1
          }
        }
        colorPlaces(color) = 0
      }

      output.println()
    }
  }

  class Solution3(input: BufferedReader, output: PrintWriter) {

    import java.util.StringTokenizer

    private val head: MyNode = new MyNode(-1)
    private var last: MyNode = head

    private def add(color: Byte): Unit = {
      last.next = new MyNode(color)
      last = last.next
    }

    private def findIndexAndMoveToTop(color: Byte) = {
      var index = 1
      var parent = head
      var current = head.next
      while (current.value != color) {
        parent = current
        current = parent.next
        index += 1
      }
      if (current == last) {
        last = parent
      }
      parent.next = current.next
      current.next = head.next
      head.next = current
      index
    }

    def solve(): Unit = {
      val prms = new StringTokenizer(input.readLine())
      val deckSize, qs = prms.nextToken.toInt

      val deckParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until deckSize) {
        add(deckParser.nextToken.toByte)
      }

      val qParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until qs) {
        val color = qParser.nextToken.toByte
        val place = findIndexAndMoveToTop(color)
        output.print(place)
        output.print(' ')
      }

      output.println()
    }
  }

  class MyNode(val value: Byte) {
    var next: MyNode = _
  }

}

import java.io.PrintWriter

object P1511C {

  import java.io.{BufferedReader, StringReader}

  def main(args: Array[String]): Unit = {
    import scala.io.Source
    val input = Source.stdin.bufferedReader()
    //val input = Source.fromFile("input.txt").bufferedReader()
    //val input = new BufferedReader(new StringReader("7 5\n2 1 1 4 3 3 1\n3 2 1 1 4"))
    //    val input = new BufferedReader(new StringReader(
    //      """3 3
    //      1 2 3
    //      1 3 1
    //    """))
    val output = new PrintWriter(System.out)
    val executor = new Solution3(input, output)
    val startTime = System.currentTimeMillis()
    executor.solve()
    output.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1(input: BufferedReader, output: PrintWriter) {

    import java.util
    import java.util.StringTokenizer

    def solve(): Unit = {
      val prms = new StringTokenizer(input.readLine())
      val deckSize = prms.nextToken().toInt
      val qs = prms.nextToken().toInt
      val deckParser = new StringTokenizer(input.readLine())
      val deck = new util.LinkedList[Byte]()
      for (_ <- 0 until deckSize) {
        deck.add(deckParser.nextToken().toByte)
      }
      val qParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until qs) {
        val color = qParser.nextToken().toByte
        val index = deck.indexOf(color)
        output.print(index + 1)
        output.print(' ')
        deck.remove(index)
        deck.addFirst(color)
      }
      output.println()
    }
  }

  class Solution2(input: BufferedReader, output: PrintWriter) {

    import java.util.StringTokenizer

    def solve(): Unit = {
      val prms = new StringTokenizer(input.readLine())
      val deckSize, qs = prms.nextToken.toInt

      val deckParser = new StringTokenizer(input.readLine())
      val colorPlaces = Array.fill[Int](51)(99)
      for (place <- 0 until deckSize) {
        val color = deckParser.nextToken.toInt
        if (colorPlaces(color) == 99) {
          colorPlaces(color) = place
        }
      }

      val qParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until qs) {
        val color = qParser.nextToken.toInt
        val place = colorPlaces(color)
        output.print(place + 1)
        output.print(' ')
        for (clr <- colorPlaces.indices) {
          val plc = colorPlaces(clr)
          if (plc < place) {
            colorPlaces(clr) = plc + 1
          }
        }
        colorPlaces(color) = 0
      }

      output.println()
    }
  }

  class Solution3(input: BufferedReader, output: PrintWriter) {

    import java.util.StringTokenizer

    private val head: MyNode = new MyNode(-1)
    private var last: MyNode = head

    private def add(color: Byte): Unit = {
      last.next = new MyNode(color)
      last = last.next
    }

    private def findIndexAndMoveToTop(color: Byte) = {
      var index = 1
      var parent = head
      var current = head.next
      while (current.value != color) {
        parent = current
        current = parent.next
        index += 1
      }
      if (current == last) {
        last = parent
      }
      parent.next = current.next
      current.next = head.next
      head.next = current
      index
    }

    def solve(): Unit = {
      val prms = new StringTokenizer(input.readLine())
      val deckSize, qs = prms.nextToken.toInt

      val deckParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until deckSize) {
        add(deckParser.nextToken.toByte)
      }

      val qParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until qs) {
        val color = qParser.nextToken.toByte
        val place = findIndexAndMoveToTop(color)
        output.print(place)
        output.print(' ')
      }

      output.println()
    }
  }

  class MyNode(val value: Byte) {
    var next: MyNode = _
  }

}

object P1511C {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter, StringReader}
  import java.util.LinkedList
  import java.util.StringTokenizer

  def main(_argv: Array[String]): Unit = {
    val input = new BufferedReader(new InputStreamReader(System.in))
    //val input = new BufferedReader(new StringReader("7 5\n2 1 1 4 3 3 1\n3 2 1 1 4"))
    val output = new PrintWriter(System.out)
    val executor = new Solution(input, output)
    executor.solve()
    output.close()
  }

  class Solution(input: BufferedReader, output: PrintWriter) {

    def solve(): Unit = {
      val prms = new StringTokenizer(input.readLine())
      val deckSize = prms.nextToken().toInt
      val qs = prms.nextToken().toInt
      val deckParser = new StringTokenizer(input.readLine())
      var deck = new LinkedList[Byte]()
      for (_ <- 0 until deckSize) {
        deck.add(deckParser.nextToken().toByte)
      }
      val qParser = new StringTokenizer(input.readLine())
      for (_ <- 0 until qs) {
        val color = qParser.nextToken().toByte
        val index = deck.indexOf(color)
        output.print(index + 1)
        output.print(' ')
        deck.remove(index)
        deck.addFirst(color)
      }
      output.println()
    }
  }

}

import java.io._
import java.util

object P1511C extends App {
  val br = new BufferedReader(new InputStreamReader(System.in))
  def readInt = br.readLine().toInt
  def readArray = br.readLine().split(" ").map(_.toInt)
  val Array(n, q) = readArray
  val color = new util.LinkedList[Int]()
  readArray foreach { i =>
    color.add(i)
  }
  val query = readArray
  val ans = query map { i =>
    val firstIndex = color.indexOf(i)
    color.remove(firstIndex)
    color.addFirst(i)
    firstIndex + 1
  }
  println(ans.mkString(" "))
}