There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row. The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.

On the first line print integer k — the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val l = data.indices.foldLeft((Set.empty[Int], List.empty[(Int, Int)], 0)) {
    case ((set, list, start), i) if set.isEmpty => (set + data(i), list, i)
    case ((set, list, start), i) if set.contains(data(i)) => (Set.empty[Int], (start + 1, i + 1) :: list, i)
    case ((set, list, start), i) => (set + data(i), list, start)
  }._2
  if (l.isEmpty)
    println(-1)
  else {
    println(l.length)
    println(l.tail.reverse.map(i => s"${i._1} ${i._2}").mkString("\n"))
    println(s"${l.head._1} ${data.length}")
  }
}

import io.StdIn._

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 n = readLine().toInt

    val a = readInts(n)

    val s = HashSet.empty[Int]
    val sb = ArrayBuilder.make[(Int, Int)]()

    var k = 0
    var b = 0

    for (i <- 0 to n-1) {
      if (s.contains(a(i))) {
        k += 1
        sb += ((b + 1, i + 1))
        s.clear()
        b = i + 1
      } else {
        s.add(a(i))
      }
    }

    if (k == 0) println(-1)
    else {
      println(k)
      val res = sb.result()
      res(res.length-1) = (res.last._1, n)
      res.foreach{ case (x, y) => println(x + " " + y)}
    }

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

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val l = data.indices.foldLeft((Set.empty[Int], List.empty[(Int, Int)], 0)) {
    case ((set, list, start), i) if set.isEmpty => (set + data(i), list, i)
    case ((set, list, start), i) if set.contains(data(i)) => (Set.empty[Int], (start + 1, i + 1) :: list, i)
    case ((set, list, start), i) => (set + data(i), list, start)
  }._2
  if (l.length == 0)
    println(-1)
  else {
    println(l.length)
    println(l.reverse.map(i => s"${i._1} ${i._2}").mkString("\n"))
  }
}


One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the left of the i-th box" ("To the left of i"), "Hidden to the right of the i-th box" ("To the right of i"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.

The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like "To the left of i" and "To the right of i", where i is integer (1 ≤ i ≤ n). The hints may coincide.

The answer should contain exactly one integer — the number of boxes that should necessarily be checked or "-1" if the hints are contradictory.

object P60A extends App {
  val Array(n,m) = readLine.split(" ").map(_.toInt)
  var l = n+1
  var r = 0
  for(e <- 1 to m) {
    val Array(to, the, direction, of, i) = readLine.split(" ")
    if(direction == "left") l = Math.min(l, i.toInt) else r = Math.max(r, i.toInt)
  }
  print(if (l <= r+1) -1 else l-r-1)
}


Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.

The first line contains integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.

Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.

NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    var L = A.count(_ == 0)
    var R = N - L

    var i = 0
    while(L > 0 && R > 0) {
      if (A(i) == 0) L -= 1
      else R -= 1
      i += 1
    }
    out.println(i)
  }

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

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

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

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

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

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

import scala.io.StdIn
import scala.math.min

object A1143 {
  def main(args: Array[String]): Unit = {
    StdIn.readLine
    val a = StdIn.readLine.filter(_!=' ').toArray
    println(1+min(a.lastIndexOf('0'),a.lastIndexOf('1')))
  }
}

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

  override def apply(io: IO): io.type = {
    val isRight = io.read[Vector[Int]].reverse

    def chop(x: Int) = isRight.length - isRight.prefixLength(_ == x)

    val ans = chop(1) min chop(0)

    io.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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

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

object Hello extends App {

  val n = StdIn.readInt()
  val doors = StdIn.readLine().split(" ").map(_.trim.toInt)
  breakable {
    for (i <- n - 1 to 1 by -1) {
      if (doors(i) != doors(i - 1)) {
        println(i)
        break
      }
    }
  }
}

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

object A extends App {
  val Array(n) = readInts
  val a = readInts

  val ar = a.reverse

  println(n - max(ar.prefixLength(_==0), ar.prefixLength(_==1)))

  def readInts() = readLine.split(" ").map(_.toInt)
}


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

object test extends App {
	val sc = new Scanner(System.in)

	val format = sc.nextInt()
	val clockTime = sc.next().toCharArray

	if (clockTime(3) > '5')
		clockTime(3) = '5'
	if (format == 24) {
		if (clockTime(1) < '4')
			clockTime(0) = List(clockTime(0), '2').min
		else
			clockTime(0) = List(clockTime(0), '1').min
	}
	else {
		clockTime(0) = {
			if (clockTime(1) < '3')
				List(clockTime(0), '1').min
			else
				'0'
		}
		if (clockTime(1) == '0' && clockTime(0) == '0')
			clockTime(0) = '1'
	}

	println(new String(clockTime))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val format = in.next().toInt
  val Array(hours, minutes) = in.next().split(":")
  val fixedMinutes = if (minutes.toInt >= 60) s"0${minutes.last}" else minutes
  val fixedHours =
    if (format == 12 && hours == "00") s"01"
    else if (format == 12 && hours.toInt > format && hours.last == '0') s"10"
    else if (format == 12 && hours.toInt > format) s"0${hours.last}"
    else if (hours.toInt >= 24) s"0${hours.last}" else hours

  println(s"$fixedHours:$fixedMinutes")
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {
  val sc = new Scanner(System.in)

  val format = sc.nextInt()
  val s = sc.next().toCharArray
  if (format == 24) {
    if(s(1) < '4')
      s(0) = List(s(0), '2').min
    else
      s(0) = List(s(0), '1').min
  }
  else {
    if(s(1) < '3')
      s(0) = List(s(0), '1').min
    else
      s(0) = '0'
  }
  s(3) = List(s(3), '5').min
  if(format == 12 && s(0) == '0' && s(1) == '0')
    s(0) = '1'

  println(new String(s))
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    val hourHeadLimit : Int
    def predicate(hour: String): Boolean

    // "00:05"
    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else if(hour.last.toString.toInt > 0 ) s"0${hour.last}"
      else if(hour.last.toString.toInt == 0 && hour.head.toString.toInt > hourHeadLimit ) s"1${hour.last}"
      else s"0${hour.last.toString.toInt + 1}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else s"0${minutes.last}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    val hourHeadLimit = 1
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    val hourHeadLimit = 2
    def predicate(hour: String): Boolean = hour.toInt < 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object A extends App {

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

  val fmt = readLine
  val t = readLine.toCharArray

  if (fmt == "12") {
    if (t(0) == '0' && t(1) == '0') t(1) = '1'
    if (t(0) == '1' && t(1) > '2') t(1) = '1'
    if (t(0) > '1' && t(1) == '0') {
      t(0) = '1'
    }
    if (t(0) > '1' && t(1) > '0') t(0) = '0'
  } else {
    if (t(0) > '2') t(0) = '0'
    if (t(0) == '2' && t(1) > '3') t(0) = '0'
  }

  if (t(3) > '5') t(3) = '0'

  println(t.mkString)
}

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

object _722A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val f = read[Int]
    val input = read[String]

    val all = for {
      h <- if (f == 12) 1 to 12 else 0 to 23
      hh = if (h < 10) "0" + h else h.toString
      m <- 0 until 60
      mm = if (m < 10) "0" + m else m.toString
    } yield hh + ":" + mm

    val ans = all minBy {choice => choice.zip(input).count {case (a, b) => a != b}}

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

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

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

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

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

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

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): 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
      }
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val format = in.next().toInt
  val Array(hours, minutes) = in.next().split(":")
  val fixedMinutes = if (minutes.toInt >= 60) s"0${minutes.last}" else minutes
  val fixedHours =
    if (format == 12 && hours == "00") s"01"
    else if (format == 12 && hours.toInt > format && hours.last == 0) s"10"
    else if (format == 12 && hours.toInt > format) s"0${hours.last}"
    else if (hours.toInt >= 24) s"0${hours.last}" else hours

  println(s"$fixedHours:$fixedMinutes")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val format = in.next().toInt
  val Array(hours, minutes) = in.next().split(":")
  val fixedMinutes = if (minutes.toInt >= 60) s"0${minutes.last}" else minutes
  val fixedHours =
    if (format == 12 && hours == "00") s"01"
    else if (hours.toInt >= format) s"0${hours.last}" else hours

  println(s"$fixedHours:$fixedMinutes")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val format = in.next().toInt
  val Array(hours, minutes) = in.next().split(":")
  val fixedMinutes = if (minutes.toInt >= 60) s"0${minutes.last}" else minutes
  val fixedHours = if (hours.toInt >= format) s"0${hours.last}" else hours
  println(s"$fixedHours:$fixedMinutes")
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {
  val sc = new Scanner(System.in)

  val format = sc.nextInt()
  val s = sc.next().toCharArray
  if (format == 24) {
    if(s(1) < '4')
      s(0) = List(s(0), '2').min
    else
      s(0) = List(s(0), '1').min
  }
  else {
    if(s(1) < '3')
      s(0) = List(s(0), '1').min
    else
      s(0) = '0'
  }
  if(s(4) == '0')
    s(3) = List(s(3), '6').min
  else
    s(3) = List(s(3), '5').min
  if(format == 12 && s(0) == '0' && s(1) == '0')
    s(0) = '1'

  println(new String(s))
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    def predicate(hour: String): Boolean

    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else s"0${hour.last}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else s"0${minutes.last}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt >= 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    def predicate(hour: String): Boolean

    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else if(hour.last.toString.toInt > 0 ) s"0${hour.last}"
      else s"0${hour.last.toString.toInt + 1}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else s"0${minutes.last}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    def predicate(hour: Int): Boolean
    def repairHour(hour: Int): String = hour match {
      case hh if predicate(hh) => hh.toString
      case hh =>
        val (decena, unidad) = (hh.toString.head, hh.toString.last)
        s"0$unidad"
    }
    def repairMinutes(minutes: Int): String = minutes match {
      case mm if mm <= 59 && mm >= 0 => mm.toString
      case mm =>
        val unidad = mm.toString.last
        s"0$unidad"
    }
    def repair(): String = {
      val (hh, mm): Tuple2[Int, Int] = time.split(":").map(_.toInt).toList match {
        case x :: y :: Nil => (x, y)
        case _ => (0, 0)
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    def predicate(hour: Int): Boolean = hour <= 12 && hour >= 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    def predicate(hour: Int): Boolean = hour <= 24 && hour >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    val hourHeadLimit : Int
    def predicate(hour: String): Boolean

    // "00:05"
    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else if(hour.last.toString.toInt > 0 ) s"0${hour.last}"
      else if(hour.last.toString.toInt == 0 && hour.head.toString.toInt > hourHeadLimit ) s"1${hour.last}"
      else s"0${hour.last.toString.toInt + 1}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else s"0${minutes.last}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    val hourHeadLimit = 1
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    val hourHeadLimit = 2
    def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    def predicate(hour: String): Boolean

    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else if(hour.last.toString.toInt > 0 ) s"0${hour.last}"
      else s"0${hour.last.toString.toInt + 1}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else if(minutes.last.toString.toInt > 0 ) s"0${minutes.last}"
      else s"0${minutes.last.toString.toInt + 1}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

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

object _722A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val f = read[Int]
    var Array(h, m) = read[String].split(':')
    var ans = 0

    if(m.toInt > 59) {
      ans += 1
      m = "0" + m(1)
    }

    if(h.toInt > f) {
      ans += 1
      h = "0" + h(1)
    }

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

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

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

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

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

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

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): 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
      }
    }
  }
}


Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).A bill $$$x \times y$$$ fits into some wallet $$$h \times w$$$ if either $$$x \le h$$$ and $$$y \le w$$$ or $$$y \le h$$$ and $$$x \le w$$$. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.Now you are asked to perform the queries of two types:  $$$+~x~y$$$ — Polycarp earns a bill of size $$$x \times y$$$;  $$$?~h~w$$$ — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $$$h \times w$$$. It is guaranteed that there is at least one query of type $$$1$$$ before the first query of type $$$2$$$ and that there is at least one query of type $$$2$$$ in the input data.For each query of type $$$2$$$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^5$$$) — the number of queries. Each of the next $$$n$$$ lines contains a query of one of these two types:   $$$+~x~y$$$ ($$$1 \le x, y \le 10^9$$$) — Polycarp earns a bill of size $$$x \times y$$$;  $$$?~h~w$$$ ($$$1 \le h, w \le 10^9$$$) — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $$$h \times w$$$.  It is guaranteed that there is at least one query of type $$$1$$$ before the first query of type $$$2$$$ and that there is at least one query of type $$$2$$$ in the input data.

NoteThe queries of type $$$2$$$ of the example:  Neither bill fits;  Both bills fit (just checking that you got that bills can overlap);  Both bills fit (both bills are actually the same);  All bills fit (too much of free space in a wallet is not a problem);  Only bill $$$1 \times 5$$$ fit (all the others don't, thus it's "NO").

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

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

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

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

  def solve(): Unit = {
    // l <= r
    var l = 0
    var r = 0
    REP(ni()) { _ =>
      val tpe = nc()
      if (tpe == '+') {
        val x, y = ni()
        l = max(l, min(x, y))
        r = max(r, max(x, y))
      } else {
        val h, w = ni()
        if (min(h, w) >= l && max(h, w) >= r) out.println("YES")
        else out.println("NO")
      }
    }
  }

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

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

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

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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

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

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

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

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

object EDU_58_E {

  type In = (Seq[String])
  type Out = Seq[String]
  type Data = (String, Int, Int)

  def solve(in: In): Out = {
    val (xs) = in

    val as: Seq[Data] =
      xs.map(_.split(" ") match {case Array(op, x, y) => (op, x.toInt, y.toInt)})

    def loop(lines: Seq[Data], longmax: Int, shortmax: Int, out: Seq[String]): Seq[String] = lines match {
      case Seq() => out
      case line +: rest => line match {
        case ("+", x, y) => loop(rest, longmax max (x max y), shortmax max (x min y), out)
        case ("?", h, w) =>
          val s = if (longmax <= (h max w) && shortmax <= (h min w)) "YES" else "NO"
          loop(rest, longmax, shortmax, out :+ s)
      }
    }

    loop(as, 0, 0, Vector.empty)
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = i.getLines(i.int)
  def formatOut(out: Out): String  = out.mkString("\n")

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each query print one integer in a single line — the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing described operation an arbitrary (possibly, zero) number of times.

NoteIn the first query of the example you can apply the following sequence of operations to obtain $$$3$$$ elements divisible by $$$3$$$: $$$[3, 1, 2, 3, 1] \rightarrow [3, 3, 3, 1]$$$.In the second query you can obtain $$$3$$$ elements divisible by $$$3$$$ with the following sequence of operations: $$$[1, 1, 1, 1, 1, 2, 2] \rightarrow [1, 1, 1, 1, 2, 3] \rightarrow [1, 1, 1, 3, 3] \rightarrow [2, 1, 3, 3] \rightarrow [3, 3, 3]$$$.

object CF565B extends App {

  import scala.io.StdIn

  val t = StdIn.readInt
  for (_ <- 0 until t) {
    val n = StdIn.readInt
    val as = StdIn.readLine.split(" ").map(_.toInt)

    val mod3_0 = as.count(_ % 3 == 0)
    val mod3_1 = as.count(_ % 3 == 1)
    val mod3_2 = as.count(_ % 3 == 2)

    val combine1_2 = Math.min(mod3_1, mod3_2)

    val remaining1 = (mod3_1 - combine1_2) / 3
    val remaining2 = (mod3_2 - combine1_2) / 3

    println(mod3_0 + combine1_2 + remaining1 + remaining2)
  }
}

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

  override def apply(io: IO): io.type = {
    val inputs = io.read[Seq[Seq[Int]]]
    val ans = inputs.map(solve)
    io.writeLines(ans)
  }

  def solve(input: Seq[Int]) = {
    val table = input
      .groupBy(_%3)
      .mapValues(_.length)
      .withDefaultValue(0)
    val rest = if (table(2) > table(1)) {
      table(1) + (table(2) - table(1))/3
    } else {
      table(2) + (table(1) - table(2))/3
    }
    table(0) + rest
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

object Main {
  def main(args: Array[String]) {
    val q = readInt
    (1 to q).map(_ => {
      val n = readInt
      val s = readLine.split(" ").map(_.toInt).map(x => x % 3)
      val cnt3 = s.count(_ == 0)
      val cnt1 = s.count(_ == 1)
      val cnt2 = s.count(_ == 2)
      if (cnt1 > cnt2) {
        println(cnt3 + cnt2 + (cnt1 - cnt2) / 3)
      } else {
        println(cnt3 + cnt1 + (cnt2 - cnt1) / 3)
      }
    })
  }
}

import java.util
import java.util.Scanner

import scala.io.StdIn

object Btask565 extends App {

  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()

  val q = new util.ArrayList[Int]()

  for (i <- 0 until n) {
    line = new Scanner(StdIn.readLine())
    val q = line.nextInt()
    var x = StdIn.readLine().split(' ').map(_.toInt)

    var count0 = 0
    var count1 = 0
    var count2 = 0

    for (i <- 0 until q) {
      val temp = x(i) % 3
      if (temp == 0) {
        count0 += 1
      }
      if (temp == 1) {
        count1 += 1
      }
      if (temp == 2) {
        count2 += 1
      }
    }
    var result = 0
    if (count1 == count2) {
      result = count0 + ((count1 + count2) / 2)
      println(result)
    } else {
      if (count1 > count2) {
        result = count0 + count2 + ((count1 - count2) / 3)
        println(result)
      } else {
        result = count0 + count1 + ((count2 - count1) / 3)
        println(result)
      }
    }
  }
  }


The Olympic Games have just started and Federico is eager to watch the marathon race.There will be $$$n$$$ athletes, numbered from $$$1$$$ to $$$n$$$, competing in the marathon, and all of them have taken part in $$$5$$$ important marathons, numbered from $$$1$$$ to $$$5$$$, in the past. For each $$$1\le i\le n$$$ and $$$1\le j\le 5$$$, Federico remembers that athlete $$$i$$$ ranked $$$r_{i,j}$$$-th in marathon $$$j$$$ (e.g., $$$r_{2,4}=3$$$ means that athlete $$$2$$$ was third in marathon $$$4$$$).Federico considers athlete $$$x$$$ superior to athlete $$$y$$$ if athlete $$$x$$$ ranked better than athlete $$$y$$$ in at least $$$3$$$ past marathons, i.e., $$$r_{x,j}<r_{y,j}$$$ for at least $$$3$$$ distinct values of $$$j$$$.Federico believes that an athlete is likely to get the gold medal at the Olympics if he is superior to all other athletes.Find any athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes), or determine that there is no such athlete.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 50\,000$$$) — the number of athletes. Then $$$n$$$ lines follow, each describing the ranking positions of one athlete. The $$$i$$$-th of these lines contains the $$$5$$$ integers $$$r_{i,1},\,r_{i,2},\,r_{i,3},\,r_{i,4},\, r_{i,5}$$$ ($$$1\le r_{i,j}\le 50\,000$$$) — the ranking positions of athlete $$$i$$$ in the past $$$5$$$ marathons. It is guaranteed that, in each of the $$$5$$$ past marathons, the $$$n$$$ athletes have distinct ranking positions, i.e., for each $$$1\le j\le 5$$$, the $$$n$$$ values $$$r_{1,j},\, r_{2, j},\, \dots,\, r_{n, j}$$$ are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$50\,000$$$.

For each test case, print a single integer — the number of an athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes). If there are no such athletes, print $$$-1$$$. If there is more than such one athlete, print any of them.

NoteExplanation of the first test case: There is only one athlete, therefore he is superior to everyone else (since there is no one else), and thus he is likely to get the gold medal.Explanation of the second test case: There are $$$n=3$$$ athletes.   Athlete $$$1$$$ is superior to athlete $$$2$$$. Indeed athlete $$$1$$$ ranks better than athlete $$$2$$$ in the marathons $$$1$$$, $$$2$$$ and $$$3$$$.  Athlete $$$2$$$ is superior to athlete $$$3$$$. Indeed athlete $$$2$$$ ranks better than athlete $$$3$$$ in the marathons $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$.  Athlete $$$3$$$ is superior to athlete $$$1$$$. Indeed athlete $$$3$$$ ranks better than athlete $$$1$$$ in the marathons $$$3$$$, $$$4$$$ and $$$5$$$. Explanation of the third test case: There are $$$n=3$$$ athletes.   Athlete $$$1$$$ is superior to athletes $$$2$$$ and $$$3$$$. Since he is superior to all other athletes, he is likely to get the gold medal.  Athlete $$$2$$$ is superior to athlete $$$3$$$.  Athlete $$$3$$$ is not superior to any other athlete. Explanation of the fourth test case: There are $$$n=6$$$ athletes.   Athlete $$$1$$$ is superior to athletes $$$3$$$, $$$4$$$, $$$6$$$.  Athlete $$$2$$$ is superior to athletes $$$1$$$, $$$4$$$, $$$6$$$.  Athlete $$$3$$$ is superior to athletes $$$2$$$, $$$4$$$, $$$6$$$.  Athlete $$$4$$$ is not superior to any other athlete.  Athlete $$$5$$$ is superior to athletes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$6$$$. Since he is superior to all other athletes, he is likely to get the gold medal.  Athlete $$$6$$$ is only superior to athlete $$$4$$$.

import scala.collection.mutable

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

    val t = nextInt
    val res = Array.fill(t)(1)

    case class A(r: Array[Int], idx: Int) extends Comparable[A] {
      override def compareTo(o: A): Int = {
          var i, l, g = 0
          while (i < 5) {
            if (r(i) < o.r(i)) l += 1
            else if (r(i) > o.r(i)) g += 1
            i += 1
          }
          if (l >= 3) -1
          else if (g >= 3) 1
          else 0
      }
    }

    for (test <- 0 until t) {
      val n = nextInt
      val rs = Array.tabulate(n) { i => A(nextInts(5), i) }

      if (n > 1) {
        val pq = new java.util.PriorityQueue[A]
        for (r <- rs) pq.add(r)
        val top = pq.peek()
        var ok = true
        for (i <- rs.indices) {
          if (top.idx != rs(i).idx && top.compareTo(rs(i)) >= 0) {
            ok = false
          }
        }
        if (ok) res(test) = top.idx + 1
        else res(test) = -1
      }

    }

    out.println(res.mkString("\n"))
    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 B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n     = readInt()
    val ranks = Array.fill(n)(readLine().split(" ").map(_.toInt))

    def compare(i: Int, j: Int): Boolean = (ranks(i) zip ranks(j)).count { case (a, b) => a <= b } >= 3

    val athlete = {
      val i = (1 until n).foldLeft(0) { (i, j) => if (compare(j, i)) j else i }
      (0 until n).forall(j => compare(i, j)) match {
        case true => Some(i)
        case _    => None
      }
    }

    athlete match {
      case Some(i) => println(i + 1)
      case _       => println(-1)
    }
  }
}

object B {

  /** TODO: Check! */
  private val multipleTests: Boolean = true

  def run(testNum: Int): Unit = {
    val n = int()
    val r = (1 to n).map(_ => Seq.fill(5)(int()))

    def winner(i: Int, j: Int): Int =
      if (r(i).zip(r(j)).count { case (a, b) => a < b } >= 3) i else j

    val potential = (1 until n).foldLeft(0) { case (ac, i) => winner(ac, i) }
    val won = (0 until n).count(i => winner(potential, i) == i) == 1
    println(if (won) potential + 1 else -1)
  }

  /** Template. */

  private val onlineJudge = System.getProperty("ONLINE_JUDGE") != null

  def main(args: Array[String]): Unit = {
    val t = if (multipleTests) reader.int() else 1
    (1 to t).foreach(run)
  }

  /** I/O. */

  import java.io._
  import java.nio.file._

  private val inputFileName = "input.txt"
  private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)

  private def string(): String = reader.string()
  private def int(): Int = reader.int()
  private def long(): Long = reader.long()
  private def double(): Double = reader.double()

  final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {
    import java.util.StringTokenizer

    def string(): String = next()
    def line(): String = tokenizer().get.nextToken("\n\r")
    def boolean(): Boolean = next().toBoolean
    def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
    def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
    def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
    def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
    def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
    def float(): Float = next().toFloat
    def double(): Double = next().toDouble
    def bigDecimal(): BigDecimal = BigDecimal(next())
    def lineNumber(): Int = linedDelegate.getLineNumber

    @inline def nextLine(): String = {
      current = None // reset the rest of current line
      delegate.readLine()
    }

    override def hasNext: Boolean = tokenizer().nonEmpty
    override def next(): String = tokenizer().getOrElse(throw new RuntimeException("End of input")).nextToken()
    override def close(): Unit = delegate.close()

    private lazy val linedDelegate = new LineNumberReader(delegate)
    private val tokenizers = Iterator.continually(delegate.readLine())
      .takeWhile(_ != null)
      .map(new StringTokenizer(_))
      .filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

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

  object FastReader {
    import scala.io.Codec

    def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)
    def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {
      Files.newBufferedReader(Paths.get(fileName), codec.charSet)
    }
    def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))
    def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {
      new BufferedReader(new InputStreamReader(inputStream, codec.charSet))
    }
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n         = readInt()
    val ranks     = Array.fill(n)(readLine().split(" ").map(_.toInt))
    val marathons = ranks.transpose.map(_.zipWithIndex.sorted)

    val counts = Array.fill(n)(0L)
    marathons.foreach { marathon =>
      marathon.indices.foreach { i =>
        val (_, athlete) = marathon(i)
        counts(athlete) += n - i - 1L
      }
    }

    val athlete = {
      val (_, i) = counts.zipWithIndex.maxBy(_._1)

      (0 until n).forall { j =>
        (0 until 5).count(k => ranks(i)(k) <= ranks(j)(k)) >= 3
      } match {
        case true => Some(i + 1)
        case _    => None
      }
    }

    athlete match {
      case Some(i) => println(i)
      case _       => println(-1)
    }
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n         = readInt()
    val ranks     = Array.fill(n)(readLine().split(" ").map(_.toInt))
    val marathons = ranks.transpose.map(_.zipWithIndex.sorted)

    val counts = Array.fill(n)(0)
    marathons.foreach { marathon =>
      marathon.indices.foreach { i =>
        val (_, athlete) = marathon(i)
        counts(athlete) += n - i - 1
      }
    }

    val athlete = {
      val (_, i) = counts.zipWithIndex.maxBy(_._1)

      (0 until n).forall { j =>
        (0 until 5).count(k => ranks(i)(k) <= ranks(j)(k)) >= 3
      } match {
        case true => Some(i + 1)
        case _    => None
      }
    }

    athlete match {
      case Some(i) => println(i)
      case _       => println(-1)
    }
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val ms =
      Array
        .fill(n)(readLine().split(" ").map(_.toInt))
        .transpose
        .map(_.zipWithIndex.sorted)

    val counts = {
      val cs = Array.fill(n)(0)

      ms.foreach { m =>
        m.indices.foreach { i =>
          val (_, athlete) = m(i)
          cs(athlete) += n - i - 1
        }
      }

      cs.zipWithIndex.sortBy(_._1)(Ordering[Int].reverse)
    }

    val (count, athlete) = counts.head

    if (count >= 3 * (n - 1) && counts.tail.forall { case (c, _) => count - c > 2 })
      println(athlete + 1)
    else
      println(-1)
  }
}


For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it!  Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.For completing the chamber Wheatley needs $$$n$$$ cubes. $$$i$$$-th cube has a volume $$$a_i$$$.Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $$$i>1$$$, $$$a_{i-1} \le a_i$$$ must hold.To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any $$$i>1$$$ you can exchange cubes on positions $$$i-1$$$ and $$$i$$$.But there is a problem: Wheatley is very impatient. If Wheatley needs more than $$$\frac{n \cdot (n-1)}{2}-1$$$ exchange operations, he won't do this boring work.Wheatly wants to know: can cubes be sorted under this conditions?

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$) — number of cubes. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — volumes of cubes. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.

NoteIn the first test case it is possible to sort all the cubes in $$$7$$$ exchanges.In the second test case the cubes are already sorted.In the third test case we can make $$$0$$$ exchanges, but the cubes are not sorted yet, so the answer is "NO".

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach { k =>
       val n = readInt
       val a = readLine.split(" ").map(_.toInt)
       val d = a.sortBy(x => -x)
       if ((d.distinct.size == n) && (d.sameElements(a))) println("NO") else println("YES")
    }
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").view.map(_.toInt)

    val status = (an zip an.tail).exists { case (a, b) => a <= b }

    val ans = status match {
      case true => "YES"
      case _    => "NO"
    }

    println(ans)
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readLong()
    val an = readLine().split(" ").map(_.toInt)
    val bn = an.sorted

    val count = (an zip bn).count { case (a, b) => a != b }
    val ans   = if ((count + 1) / 2 <= n * (n - 1) / 2 - 1) "YES" else "NO"

    println(ans)
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readLong()
    val an = readLine().split(" ").map(_.toInt)
    val bn = an.sorted

    val count = (an zip bn).count { case (a, b) => a != b }
    val ans   = if (count <= n * (n - 1) / 2 - 1) "YES" else "NO"

    println(ans)
  }
}


Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total.Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod.

The first line contains four integers n, m, b, mod (1 ≤ n, m ≤ 500, 0 ≤ b ≤ 500; 1 ≤ mod ≤ 109 + 7) — the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of bugs per line for each programmer.

Print a single integer — the answer to the problem modulo mod.

object C544{
  def main(args: Array[String]){

    var Array(n,m,b,mod)=readLine.split(" ").map(_.toInt)

    var A=readLine.split(" ").map(_.toInt)
    var dp=Array.ofDim[Int](2,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))
          }
          dp(i&1)(j)(k)%=mod
        }
      }
    }
    var ans:Int=0
    for(i<-0 to b){
      ans+=dp(n&1)(m)(i)
      ans%=mod
    }
    println(ans)
  }
}

object C544{
  def main(args: Array[String]){

    val Array(n,m,b,mod)=readLine.split(" ").map(_.toInt)

    val A=readLine.split(" ").map(_.toInt)
    var dp=Array.ofDim[Int](2,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))
          }
          dp(i&1)(j)(k)%=mod
        }
      }
    }
    var ans:Int=0
    for(i<-0 to b){
      ans+=dp(n&1)(m)(i)
      ans%=mod
    }
    println(ans)
  }
}

object C544{
  def main(args: Array[String]){

    var Array(n,m,b,mod)=readLine.split(" ").map(_.toInt)

    var A=readLine.split(" ").map(_.toInt)
    val dp=Array.ofDim[Int](2,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))
          }
          dp(i&1)(j)(k)%=mod
        }
      }
    }
    var ans:Int=0
    for(i<-0 to b){
      ans+=dp(n&1)(m)(i)
      ans%=mod
    }
    println(ans)
  }
}

object C544{
  def main(args: Array[String]){

    val Array(n,m,b,mod)=readLine.split(" ").map(_.toInt)

    val A=readLine.split(" ").map(_.toInt)
    val dp=Array.ofDim[Int](2,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))
          }
          dp(i&1)(j)(k)%=mod
        }
      }
    }
    var ans:Int=0
    for(i<-0 to b){
      ans+=dp(n&1)(m)(i)
      ans%=mod
    }
    println(ans)
  }
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.mutable.ArrayBuffer

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def lowerBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (!(array(mid) < value)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val (n, m, b, mod) = (nextInt, nextInt, nextInt, nextInt)
    val dp = Array.ofDim[Int](m + 1, b + 1)
    val a: Array[Int] = new Array(n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    dp(0)(0) = 1
    for (k <- 0 until n) {
      for (i <- 0 until m) {
        for (j <- 0 to b) {
          if (j + a(k) <= b) {
            dp(i + 1)(j + a(k)) += dp(i)(j)
            dp(i + 1)(j + a(k)) %= mod
          }
        }
      }
    }
    var res = 0
    for (i <- 0 to b) {
      res += dp(m)(i)
      res %= mod
    }
    out.println(res)
  }

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

object C544 {
    def main(args: Array[String]) {
      val Array(n, m, b, mod) = readLine.split(" ").map(_.toInt)
      val A = readLine.split(" ").map(_.toInt)
      val dp = Array.ofDim[Int](2, m + 10, b + 10)
      dp(0)(0)(0) = 1
      for (i <- 1 to n) {
        for (j <- 0 to m) {
          for (k <- 0 to b) {
            dp(i & 1)(j)(k) = dp(1 - (i & 1))(j)(k)
            if (j > 0 && k >= A(i - 1)) {
              dp(i & 1)(j)(k) += (dp(i & 1)(j - 1)(k - A(i - 1)))
            }
            dp(i & 1)(j)(k) %= mod
          }
        }
      }
      var ans: Int = 0
      for (i <- 0 to b) {
        ans += dp(n & 1)(m)(i)
        ans %= mod
      }
      println(ans)
    }
  }

/**
 * Created by canoe on 5/17/15.
 */

object CF544A {
  def main(args: Array[String]) {
    val Array(n, m, b, mod) = readLine().split(" ").map(_.toInt)
    val A = readLine().split(" ").map(_.toInt)
    val dp = Array.ofDim[Int](2, m + 8, b + 8)

    dp(0)(0)(0) = 1
    for (i <- 1 to n) {
      for (j <- 0 to m) {
        for (k <- 0 to b) {
          dp(i & 1)(j)(k) = dp(1 - (i & 1))(j)(k)
          if (k >= A(i - 1) && j >= 1) {
            dp(i & 1)(j)(k) += dp(i & 1)(j - 1)(k - A(i - 1))
          }
          dp(i & 1)(j)(k) %= mod
        }
      }
    }

    var answer: Int = 0
    for (i <- 0 to b) {
      answer += dp(n & 1)(m)(i)
      answer %= mod;
    }
    println(answer)
  }
}

object C544{
  def main(args: Array[String]){

    var Array(n,m,b,mod)=readLine.split(" ").map(_.toInt)

    var A=readLine.split(" ").map(_.toInt)
    var dp=Array.ofDim[Int](n+10,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i)(j)(k)=dp(i-1)(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i)(j)(k)+=(dp(i)(j-1)(k-A(i-1)))
          }
          dp(i)(j)(k)%=mod
        }
      }
    }
    println(dp(n)(m)(b))
  }
}