Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.

The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house. The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.

Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.

NoteIn the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6. In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val houses = in.next()
  val distinct = houses.distinct
  val result = houses.indices.foldLeft(0, Map.empty[Char, Int], Int.MaxValue) {
    case ((x, map, found), el) =>
      var nX = x
      val ch = houses(el)
      var nMap = map + (ch -> (map.getOrElse(ch, 0) + 1))
      if (nMap.size == distinct.length) {
        while (nMap.size == distinct.length) {
          val nEl = houses(el - nX)
          if (nMap(nEl) == 1)
            nMap = nMap - nEl
          else
            nMap = nMap + (nEl -> (nMap(nEl) - 1))
          nX -= 1
        }
        val t = (nX + 1, nMap, Math.min(nX + 2, found))
        t
      }
      else (nX + 1, nMap, found)
  }
  println(result._3)

}

object C701 {

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

  val MAX = 60

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val str = read.toCharArray
    val desiredCount = {
      val arr = Array.fill(MAX)(0)
      str.foreach { ch => arr(ch - 'A') = 1 }
      arr
    }

    if(desiredCount.sum == 1) {
      out.println(1)
    } else {
      val countTill = Array.fill(n+1)(Array.fill(MAX)(0))

      for (i <- 0 until n) {
        countTill(i).copyToArray(countTill(i+1))
        countTill(i+1)(str(i) - 'A') += 1
      }

      def checkValid(i: Int, j: Int): Boolean = {
        var x = 0
        var res = true
        while(x < MAX) {
          res &= countTill(j+1)(x) - countTill(i)(x) >= desiredCount(x)
          x += 1
        }
        res
      }

      var res = Int.MaxValue

      for (i <- 0 until n) {
        var low = i
        var high = n - 1

        while (low < high) {
          val mid = low + (high - low) / 2
//          println(low, high, mid)

          if (checkValid(i, mid))
            high = mid
          else
            low = mid + 1

//          println(low, high, mid)
        }
//        println(i, low)
        if(checkValid(i, low))
          res = math.min(res, low-i+1)
      }

      out.println(res)
    }

    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

//package c

object C 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 Array(n) = readInts(1)
  val s = readLine.toCharArray

  val cs = s.distinct.zipWithIndex.toMap
  val pokemons = cs.size
  val as = s.map(cs)
  val cnts = Array.fill(pokemons)(0)

  var l, r = 0
  var res = n

  def isOk() = {
    var i = 0
    var ok = true
    while (ok && i < pokemons) {
      if (cnts(i) == 0) ok = false
      i += 1
    }
    ok
  }

  while (r < n) {
    cnts(as(r)) += 1
    r += 1
    while (isOk()) {
      res = math.min(res, r - l)
      cnts(as(l)) -= 1
      l += 1
    }
  }

  println(res)
}

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

object _701C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val (n, houses) = read[(Int, String)]
    val all = houses.distinct.length

    def solve(l: Int, r: Int, count: mutable.Map[Char, Int]): Int = {
      if (count.keys.size == all) {
        val c = houses(l)
        count(c) = count(c) - 1
        if (count(c) <= 0) count.remove(c)
        (r - l) min solve(l+1, r, count)
      } else if (r < n) {
        val c = houses(r)
        count(c) += 1
        solve(l, r + 1, count)
      } else {
        Int.MaxValue
      }
    }

    val ans = solve(0, 0, map[Char] to 0)
    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 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 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, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

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

object _701C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val (n, houses) = read[(Int, String)]
    val all = houses.distinct.size

    def solve(l: Int, r: Int, count: mutable.Map[Char, Int]): Int = {
      debug(l, r, count)
      if (count.keys.size == all) {
        val c = houses(l)
        if(count contains c) {
          count(c) = count(c) - 1
          if (count(c) <= 0) count.remove(c)
        }
        (r - l) min solve(l+1, r, count)
      } else if (r < n) {
        val c = houses(r)
        count(c) += 1
        solve(l, r + 1, count)
      } else {
        Int.MaxValue
      }
    }

    val ans = solve(0, 0, map[Char] to 0)
    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 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 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, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    sc.nextLine()
    val s = sc.nextLine()

    //
    val vol = 65
    var num = 0

    val dp2 = new Array[Boolean](58)
    for(c <- s){
      if(!dp2(c.toInt - vol)){
        num += 1
        dp2(c.toInt - vol) = true
      }
    }

    var ans = n
    var l = 0
    var r = 0
    var cnt = 0

    val dp = new Array[Int](58)
    while(r < n){
      val now = s(r).toInt - vol

      if(dp(now) == 0){
        cnt += 1
        dp(now) += 1
        if(cnt == num){
          ans = Math.min(ans, r-l+1)

          // move l
          var flag = true
          while(flag){
            val tmp = s(l).toInt - vol
            dp(tmp) -= 1
            l += 1
            if(dp(tmp) == 0){
              cnt -= 1
              flag = false
            }
            else
              ans = Math.min(ans, r-l+1)
          }

        }
      }
      else{
        dp(now) += 1
      }
      r += 1
    }

    println(ans)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val houses = in.next()
  val distinct = houses.distinct
  val result = houses.indices.foldLeft(0, Map.empty[Char, Int], Int.MaxValue) {
    case ((x, map, found), el) =>
      var nX = x
      val ch = houses(el)
      var nMap = map + (ch -> (map.getOrElse(ch, 0) + 1))
      if (nMap.size == distinct.length) {
        while (nMap.size == distinct.length) {
          val nEl = houses(el - nX)
          if (nMap(nEl) == 1)
            nMap = nMap - nEl
          else
            nMap = nMap + (nEl -> (nMap(nEl) - 1))
          nX -= 1
        }
        (nX + 2, nMap, Math.min(nX + 2, found))
      }
      else (nX + 1, nMap, found)
  }
  println(result._3)

}

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

object _701C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val (n, houses) = read[(Int, String)]

    val first = map[Char] to Int.MaxValue
    val last = map[Char] to Int.MinValue

    houses.zipWithIndex foreach {case (c, i) =>
      first(c) = first(c) min i
      last(c) = last(c) max i
    }
    val (p1, p2, p3, p4) = (first.values.min, first.values.max, last.values.min, last.values.max)
    val ans = (p2 - p1) min (p4  - p3)
    write(ans + 1)
  }
}
/****************************[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 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 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, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

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

object _701C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val (n, houses) = read[(Int, String)]
    val count = map[Char] to 0
    val all = houses.distinct.length

    var l, r = 0
    var ans = Int.MaxValue

    while(r < n) {
      count.size match {
        case `all` =>
          ans = ans min (r - l)
          l += 1
          if (l < n) {
            val h = houses(l)
            count(h) -= 1
            if (count(h) <= 0) count.remove(h)
          }
        case _ =>
          r += 1
          if (r < n) count(houses(r)) += 1
      }
    }

    write(ans min n)
  }
}
/****************************[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 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 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, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

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

object _701C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val (n, houses) = read[(Int, String)]
    val count = map[Char] to 0
    val all = houses.distinct.size

    var l, r = 0
    var ans = Int.MaxValue

    while(r < n) {
      //debug(houses, l, r, count, count.size)
      if(count.size == all) {
        ans = ans min (r - l)
        if (l < n) {
          l += 1
          val h = houses(l)
          count(h) -= 1
          if (count(h) <= 0) count.remove(h)
        }
      } else {
        r += 1
        if (r < n) count(houses(r)) += 1
      }
    }

    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 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 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, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    sc.nextLine()
    val s = sc.nextLine()

    //
    val dp = new Array[Int](58)
    val vol = 65
    var cnt = 0

    for(c <- s){
      if(dp(c.toInt - vol) == 0)
        cnt += 1

      dp(c.toInt - vol) += 1
    }

    var ans = 0
    var flag1 = false  // start
    var flag2 = false  // end

    for(c <- s){
      if(!flag2){
        val now = c.toInt - vol

        if(flag1){
          ans += 1
          if(dp(now) != 0){
            dp(now) = 0
            cnt -= 1
            if(cnt == 0)
              flag2 = true
          }
        }
        else{
          if(dp(now) == 1){
            cnt -= 1
            ans += 1
            flag1 = true
            dp(now) = 0
          }
          else
            dp(now) -= 1
        }
      }
    }

    println(ans)
  }
}


Recently Duff has been a soldier in the army. Malek is her commander.Their country, Andarz Gu has n cities (numbered from 1 to n) and n - 1 bidirectional roads. Each road connects two different cities. There exist a unique path between any two cities.There are also m people living in Andarz Gu (numbered from 1 to m). Each person has and ID number. ID number of i - th person is i and he/she lives in city number ci. Note that there may be more than one person in a city, also there may be no people living in the city.  Malek loves to order. That's why he asks Duff to answer to q queries. In each query, he gives her numbers v, u and a.To answer a query:Assume there are x people living in the cities lying on the path from city v to city u. Assume these people's IDs are p1, p2, ..., px in increasing order. If k = min(x, a), then Duff should tell Malek numbers k, p1, p2, ..., pk in this order. In the other words, Malek wants to know a minimums on that path (or less, if there are less than a people).Duff is very busy at the moment, so she asked you to help her and answer the queries.

The first line of input contains three integers, n, m and q (1 ≤ n, m, q ≤ 105). The next n - 1 lines contain the roads. Each line contains two integers v and u, endpoints of a road (1 ≤ v, u ≤ n, v ≠ u). Next line contains m integers c1, c2, ..., cm separated by spaces (1 ≤ ci ≤ n for each 1 ≤ i ≤ m). Next q lines contain the queries. Each of them contains three integers, v, u and a (1 ≤ v, u ≤ n and 1 ≤ a ≤ 10).

For each query, print numbers k, p1, p2, ..., pk separated by spaces in one line.

NoteGraph of Andarz Gu in the sample case is as follows (ID of people in each city are written next to them):

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    builder.sizeHint(limit)
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    ancestorsBuilder.sizeHint(17)
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    min10Builder.sizeHint(17)

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    var i = 0
    while (i < neighbours(u).length) {
      val v = neighbours(u)(i)
      if (v != parent) dfs(v, u, depth + 1)
      i += 1
    }
  }

  dfs(0, -1, 0)

  def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {
    var v = _v
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, min10)
  }

  def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    // now depths(v) == depths(u)
    var (v, min10) = levelAncestor(v0, depths(u), limit)
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

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

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lowestCommonAncestor(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    builder.sizeHint(limit)
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    ancestorsBuilder.sizeHint(17)
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    min10Builder.sizeHint(17)

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    for (v <- neighbours(u)) {
      if (v != parent) dfs(v, u, depth + 1)
    }
  }

  dfs(0, -1, 0)

  def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {
    var v = _v
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, min10)
  }

  def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    // now depths(v) == depths(u)
    var (v, min10) = levelAncestor(v0, depths(u), limit)
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

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

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lowestCommonAncestor(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder
import java.io.PrintWriter

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    builder.sizeHint(limit)
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    ancestorsBuilder.sizeHint(17)
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    min10Builder.sizeHint(17)

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    var i = 0
    while (i < neighbours(u).length) {
      val v = neighbours(u)(i)
      if (v != parent) dfs(v, u, depth + 1)
      i += 1
    }
  }

  dfs(0, -1, 0)

  def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {
    var v = _v
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, min10)
  }

  def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    // now depths(v) == depths(u)
    var (v, min10) = levelAncestor(v0, depths(u), limit)
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

  val out = new PrintWriter(System.out)

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lowestCommonAncestor(u, v, a)
    out.println(res.length + " " + res.mkString(" "))
  }

  out.flush()
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    builder.sizeHint(limit)
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    ancestorsBuilder.sizeHint(17)
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    min10Builder.sizeHint(17)

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    for (v <- neighbours(u)) {
      if (v != parent) dfs(v, u, depth + 1)
    }
  }

  dfs(0, -1, 0)

  def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    // now depths(v) == depths(u)
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

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

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lca(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)

  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    //ancestorsBuilder.clear()
    //min10Builder.clear()

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }
    //    var depthDelta = 1
    //    while (depthDelta <= depth) {
    //      ancestorsBuilder += path(depth - depthDelta)
    //      depthDelta <<= 1
    //    }
    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    for (v <- neighbours(u)) {
      if (v != parent) dfs(v, u, depth + 1)
    }
  }

  dfs(0, -1, 0)

  def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
        i += 1 // FIXME
      }
      i -= 1
    }
    // now depths(v) == depths(u)
    assert(depths(v) == depths(u))
//    if (ancestors(v).length != ancestors(u).length) {
//      println(ancestors(v).length, ancestors(u).length)
//      Console.flush
//      return Array.empty
//    }
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

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

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lca(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val ancestorsBuilder = new ArrayBuilder.ofInt

  val min10s = Array.ofDim[Array[Array[Int]]](n)
  val min10Builder = new ArrayBuilder.ofRef[Array[Int]]

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    ancestorsBuilder.clear()
    min10Builder.clear()

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 1
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i <= ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i - 1), 10)
        prev = ancestors(prev)(i - 1)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }
    //    var depthDelta = 1
    //    while (depthDelta <= depth) {
    //      ancestorsBuilder += path(depth - depthDelta)
    //      depthDelta <<= 1
    //    }
    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    for (v <- neighbours(u)) {
      if (v != parent) {
        dfs(v, u, depth + 1)
      }
    }
  }

  dfs(0, -1, 0)

  def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit) //Array.empty[Int]
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    //println(min10.mkString(" "))
    // now depths(v) == depths(u)
    if (ancestors(v).length != ancestors(u).length) {
      println(ancestors(v).length, ancestors(u).length)
      Console.flush
      return Array.empty
    }
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          //println(min10.mkString(" "))
          min10 = merge(min10, min10s(v)(i), limit)
          //println(min10.mkString(" "))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

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

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lca(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}


Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence .Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].

The only input line contains an integer n (1 ≤ n ≤ 105).

In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists. If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n. If there are multiple solutions, you are allowed to print any of them.

NoteFor the second sample, there are no valid sequences.

import scala.collection._

object C 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 Array(n) = readInts(1)

  var prime = true
  for (i <- 2 until n) if (n % i == 0) prime = false

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

  if (n == 4) println("YES\n1\n3\n2\n4")
  else if (prime) {
    println("YES")
    val used = mutable.BitSet(n + 1)
    var fact = BigInt(1)
    for (i <- 2 until n) fact = fact * i % n
    val as = Array.ofDim[Long](n)
    as(0) = 1
    as(n - 1) = n

    for (i <- n - 2 to 1 by -1) {
      val x = n + 1 - fact % n
      as(i) = x.toLong
      fact = fact * x.modInverse(n) % n
    }

    println(as.mkString("\n"))

  } else println("NO")

  Console.flush
}

import scala.collection._

object C 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 Array(n) = readInts(1)

  var prime = true
  for (i <- 2 until n) if (n % i == 0) prime = false

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

  if (prime) {
    println("YES")
    val used = mutable.BitSet(n + 1)
    var fact = BigInt(1)
    for (i <- 2 until n) fact = fact * i % n
    val as = Array.ofDim[Long](n)
    as(0) = 1
    as(n - 1) = n

    for (i <- n - 2 to 1 by -1) {
      val x = n + 1 - fact % n
      as(i) = x.toLong
      fact = fact * x.modInverse(n) % n
    }

    println(as.mkString("\n"))

  } else println("NO")

  Console.flush
}

import scala.collection._

object C 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 Array(n) = readInts(1)

  var prime = true
  for (i <- 2 until n) if (n % i == 0) prime = false

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

  if (n == 4) println("1\n3\n2\n4")
  else if (prime) {
    println("YES")
    val used = mutable.BitSet(n + 1)
    var fact = BigInt(1)
    for (i <- 2 until n) fact = fact * i % n
    val as = Array.ofDim[Long](n)
    as(0) = 1
    as(n - 1) = n

    for (i <- n - 2 to 1 by -1) {
      val x = n + 1 - fact % n
      as(i) = x.toLong
      fact = fact * x.modInverse(n) % n
    }

    println(as.mkString("\n"))

  } else println("NO")

  Console.flush
}