Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1, a2, ..., ak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n - k cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (ai ≠ b for every 1 ≤ i ≤ k) and choose a storage in some city s (s = aj for some 1 ≤ j ≤ k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 105, 0 ≤ k ≤ n) — the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1 ≤ u, v ≤ n, 1 ≤ l ≤ 109, u ≠ v) meaning that there is a road between cities u and v of length of l kilometers . If k > 0, then the last line of the input contains k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n) — the number of cities having flour storage located in. If k = 0 then this line is not presented in the input.

Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print  - 1 in the only line.

NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.

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

object B {
  case class Edge (
    neighbor: Int,
    weight: Int
  )

  def main(args: Array[String]): Unit = {
    /* Ugly, inherently mutable, procedural code, because we're reading standard input. */
    var bestWeight = Int.MaxValue  // for iterative reassignment at a later date...
    var flourCities = Set[Int]()
    val Array(n: Int, m: Int, k: Int) = StdIn.readLine.split(" ").map(_.toInt)
    val adjLists = Array.fill(n + 1){new MutableList[Edge]}
    1 to m foreach { _ =>
       val Array(u: Int, v: Int, l: Int) = StdIn.readLine.split(" ").map(_.toInt)
       adjLists(u) += Edge(neighbor = v, weight = l)
       adjLists(v) += Edge(neighbor = u, weight = l)
    }
    if (k > 0) {
      StdIn.readLine.split(" ").map(_.toInt).foreach { flourCities +=  _ }
    }
    flourCities.foreach { city =>
      adjLists(city).foreach { edge =>
        if (!flourCities.contains(edge.neighbor)) {
          bestWeight = math.min(bestWeight, edge.weight)
        }
      }
    }
    bestWeight = if (bestWeight == Int.MaxValue) -1 else bestWeight
    System.out.println(bestWeight)
  }
}

import scala.collection.mutable._

object Bakery {
  case class Pair(v:Int,w:Int)
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val k=arr(2)

    val graph=Array.fill[ArrayBuffer[Pair]](n)(new ArrayBuffer[Pair]())

    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt)
      graph(edge(0)-1)+=Pair(edge(1)-1,edge(2))
      graph(edge(1)-1)+=Pair(edge(0)-1,edge(2))
    }
    var stgVertexHs:HashSet[Int]=HashSet[Int]()
    if(k>0) {
      in.readLine().split(" ").map(_.toInt - 1).foreach(stgVertexHs+=_)
    }
    else {
      println("-1")
      return
    }
    var minDis=Int.MaxValue
    for(stgLoc<- stgVertexHs){
      val i=stgLoc
      for(j<- 0 until graph(i).length) {
        val edge=graph(i)(j)
        if(!stgVertexHs.contains(edge.v))
          minDis = math.min(edge.w, minDis)
      }
    }
    println(if(minDis==Int.MaxValue) "-1" else minDis)
  }
}

import scala.collection.mutable._

object Bakery {
  case class Pair(v:Int,w:Int)
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val k=arr(2)

    val graph=Array.fill[ArrayBuffer[Pair]](n)(new ArrayBuffer[Pair]())

    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt)
      graph(edge(0)-1)+=Pair(edge(1)-1,edge(2))
      graph(edge(1)-1)+=Pair(edge(0)-1,edge(2))
    }
    var stgVertex:Array[Int]=null
    var stgVertexHs:HashSet[Int]=HashSet[Int]()
    if(k>0) {
      stgVertex =in.readLine().split(" ").map(_.toInt - 1)
      stgVertex.foreach(stgVertexHs+=_)
    }
    else {
      println("-1")
      return
    }

    var minDis=Int.MaxValue
    for(k<- 0 until stgVertex.length){
      val i=stgVertex(k)
      for(j<- 0 until graph(i).length) {
        val edge=graph(i)(j)
        if(!stgVertexHs.contains(edge.v))
          minDis = math.min(edge.w, minDis)
      }
    }
    println(if(minDis==Int.MaxValue) "-1" else minDis)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val lines = in.take(m).map(_.split(' ').map(_.toInt)).toList
  if (k == 0)
    println(-1)
  else {
    val warehouses = in.next().split(' ').map(_.toInt).toSet
    val lengths = lines.filter{case(Array(u, v, l)) => List(u, v).count(warehouses) == 1}.map(_.last)
    if (lengths.isEmpty)
      println(-1)
    else
      println(lengths.min)
  }
}

object B707 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = readInts(3)
    val _G = Array.fill(n)(collection.mutable.ArrayBuffer.empty[(Int, Long)])
    for(_ <- 0 until m) {
      val Array(u, v, d) = readInts(3)
      _G(u-1) += ((v-1, d.toLong))
      _G(v-1) += ((u-1, d.toLong))
    }
    val G = _G.map(_.sortBy(_._2).toArray)
    if(k > 0) {
      val ks = readInts(k).toSet
      var min = Long.MaxValue
      for(i <- ks) {
        for(j <- G(i-1) if !ks.contains(j._1+1)) {
          min = math.min(min, j._2)
        }
      }
      if(min == Long.MaxValue) {
        println("-1")
      } else {
        println(min)
      }
    } else {
      println("-1")
    }
  }

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

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

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

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

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

}

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

object _707B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n, m, k = read[Int]
    val roads = read[Seq, (Int, Int, Int)](m)
    val isStorage = read[Set, Int](k)

    var ans = Int.MaxValue

    roads foreach {
      case (u, v, cost) =>
        if(isStorage(u) ^ isStorage(v)) {
          ans = ans min cost
        }
    }

    write(if (ans == Int.MaxValue) -1 else 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 toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, 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 = "\n"): 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._, collection.Searching._

object _707B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n, m, k = read[Int]
    val roads = read[Seq, (Int, Int, Int)](m)
    val isStorage = read[Set, Int](k)
    val ans = roads collect {
      case (u, v, cost) if isStorage(u) ^ isStorage(v) => cost
    }
    write(ans.whenNonEmpty(_.min) getOrElse -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 toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, 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 = "\n"): 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
import scala.collection.mutable.PriorityQueue

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

    val n = sc.nextInt()
    val m = sc.nextInt()
    val k = sc.nextInt()

    val road = Array.fill(n+1)(new PriorityQueue[(Int,Int)])
    for(i <- 1 to m){
      val u = sc.nextInt()
      val v = sc.nextInt()
      val l = sc.nextInt()

      road(u) += ((-l, v))
      road(v) += ((-l, u))
    }

    if(k == 0)
      println(-1)
    else{
      var ans = 1e9.toInt + 1
      val a = new Array[Int](k)
      val dp = new Array[Boolean](n+1)

      for(i <- 0 until k){
        val tmp = sc.nextInt()
        a(i) = tmp
        dp(tmp) = true
      }

      for(e <- a){
        var flag = true
        while(!road(e).isEmpty && flag){
          val tmp = road(e).dequeue
          val nowp = (-tmp._1, tmp._2)
          if(!dp(nowp._2)){
            ans = Math.min(ans, nowp._1)
            flag = false
          }
        }
      }

      if(ans == 1e9.toInt + 1)
        println(-1)
      else
        println(ans)
    }
  }
}

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

object _368B extends App {

  case class Edge(target: Int, cost: Int)

  val Array(n, m, k) = readLine().split(" ").map(_.toInt)
  val G = Array.ofDim[mutable.Set[Edge]](n + 1)
  for (i <- 1 to n) G(i) = new mutable.HashSet[Edge]

  1 to m foreach { _ =>
    val Array(u, v, cost) = readLine().split(" ").map(_.toInt)
    val U = G(u)
    val V = G(v)
    U += Edge(v, cost)
    V += Edge(u, cost)
  }

  if (k == 0) {
    println(-1)
  } else {
    val K = readLine().split(" ").map(_.toInt)
    val IsStorage = Array.ofDim[Boolean](n + 1)
    K.foreach { k =>
      IsStorage(k) = true
    }

    var min = Int.MaxValue
    K.foreach { k =>
      for (e <- G(k)) {
        val y = e.target
        if (!IsStorage(y)) {
          min = Math.min(min, e.cost)
        }
      }
    }

    println(if (min == Int.MaxValue) -1 else min)
  }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object B_368 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    //runTest(Test.sa4)
//    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line = readLine
    val nCities = line.int
    val mRoads = line.int
    val kStorages = line.int

    val roadMap = scala.collection.mutable.Map[Int, List[Road]]()
    val city = new Array[Boolean](nCities)

    for (i <- 0 until mRoads) {
      val rLine = readLine()
      val city1 = rLine.int
      val city2 = rLine.int
      val length = rLine.long
      val road1 = new Road(city1, city2, length)
      val nList1 = roadMap.getOrElse(city1, List())
      roadMap.put(city1, road1 :: nList1)
      val nList2 = roadMap.getOrElse(city2, List())
      val road2 = new Road(city2, city1, length)
      roadMap.put(city2, road2 :: nList2)
    }

    var res = -1l
    if (kStorages > 0) {
      val sLine = readLine
      val set = scala.collection.mutable.Set[Int]()
      for (i <- 0 until kStorages) {
        set.add(sLine.int)
      }
      for (stor <- set) {
        roadMap.get(stor) match {
          case Some(cityRoads) => for (road <- cityRoads) {
            if (!set.contains(road.city2) && (res == -1 || road.length < res)) {
              res = road.length
            }
          }
          case _ =>
        }
      }
    }

    //---------------------------- parameters reading :end

    outLn(res+"")
    finish
  }

//  class City(num:Int) {
//    var adj = List[
//  }

  class Road(val city1: Int, val city2: Int, val length: Long)

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

   //in all
val sa1 = """
5 7 5
1 2 3
2 4 3
3 4 2
3 5 1
3 1 10
5 2 1
2 3 1
1 2 3 4 5
"""

//no storage
val sa2 = """
5 7 0
1 2 3
2 4 3
3 4 2
3 5 1
3 1 10
5 2 1
2 3 1
"""

val sa3 = """
5 7 3
1 2 3
2 4 3
3 4 2
3 5 1
3 1 10
5 2 1
2 3 1
2 3 5
"""

val sa4 = """
2 1 1
1 2 100
2
"""
}

}

object Bakery707B   extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val m = in.nextInt()
    val k = in.nextInt()
    val nodes = (0 until n).map(i => Node(i)).toArray
    val edges = (1 to m).map{_ =>
      val a = nodes(in.nextInt()-1)
      val b = nodes(in.nextInt()-1)
      val cost = in.nextInt()
      Edge(a,b,cost)
    }

    (1 to k).foreach(_ => nodes(in.nextInt()-1).withStorage())

    val validCost = edges.flatMap{
      case Edge(a,b,cost) if a.hasStorage && !b.hasStorage => Some(cost)
      case Edge(a,b,cost) if !a.hasStorage && b.hasStorage => Some(cost)
      case _ => None
    }
    if(validCost.isEmpty){
      out.println(-1)
    }else{
      out.println(validCost.min)
    }

  }
  case class Edge(a: Node, b: Node,cost: Int)
  case class Node(id: Int){
    var hasStorage: Boolean = false
    def withStorage(): Unit = hasStorage = true
  }

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

object Bakery707B extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val m = in.nextInt()
    val k = in.nextInt()
    val nodes = (0 until n).map(i => Node(i)).toArray
    val edgesRaw: Seq[(Int,Int,Int)] = (1 to m).map{_ => (in.nextInt()-1,in.nextInt()-1,in.nextInt())}

    (1 to k).foreach(_ => {
      val node = nodes(in.nextInt()-1)
      nodes.update(node.id,node.copy(hasStorage = true))
    })

    val validCost = edgesRaw.map{
      case (a,b,c) => Edge(nodes(a),nodes(b),c)
    }.flatMap{
      case Edge(Node(_,true),Node(_,false),cost)  => Some(cost)
      case Edge(Node(_,false),Node(_,true),cost)  => Some(cost)
      case _ => None
    }
    if(validCost.isEmpty){
      out.println(-1)
    }else{
      out.println(validCost.min)
    }

  }
  case class Edge(a: Node, b: Node,cost: Int)
  case class Node(id: Int, hasStorage: Boolean = false)

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

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

object B {
  def main(args: Array[String]): Unit = {
    /* Ugly, inherently mutable, procedural code, because we're reading standard input. */
    var bestWeight = Int.MaxValue  // for iterative reassignment at a later date...
    var flourCities = Set[Int]()
    val Array(n: Int, m: Int, k: Int) = StdIn.readLine.split(" ").map(_.toInt)
    val adjMat: Array[Array[Option[Int]]] =
      Array.fill(n + 1) {
        Array.fill(n + 1) {
          None
        }
      }
    1 to m foreach { _ =>
       val Array(u: Int, v: Int, l: Int) = StdIn.readLine.split(" ").map(_.toInt)
       adjMat(u)(v) = Some(l)
       adjMat(v)(u) = Some(l)
    }
    if (k > 0) {
      StdIn.readLine.split(" ").map(_.toInt).foreach { flourCities +=  _ }
    }
    flourCities.foreach { city =>
      1 to n foreach { adjCity =>
        if (!flourCities.contains(adjCity)) {
          val edgeWeight = adjMat(city)(adjCity)
          edgeWeight match {
            case Some(candidateWeight) => bestWeight = math.min(bestWeight, candidateWeight)
            case None =>
          }
        }
      }
    }
    bestWeight = if (bestWeight == Int.MaxValue) -1 else bestWeight
    System.out.println(bestWeight)
  }
}

import scala.collection.mutable._

object Bakery {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val k=arr(2)

    val graph=Array.fill[Int](n,n)(Int.MaxValue)

    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt)
      graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))
    }
    var stgVertex:Array[Int]=null
    if(k>0) {
      stgVertex =in.readLine().split(" ").map(_.toInt - 1)
    }
    else {
      println("-1")
      return
    }
    var minDis=Int.MaxValue
    for(i<- 0 until stgVertex.length){
      if(i!=0){
        minDis=math.min(graph(i)(i-1),minDis)
      }
      if(i!=stgVertex.length-1){
        minDis=math.min(graph(i)(i+1),minDis)
      }
    }

    println(if(minDis==Int.MaxValue) "-1" else minDis)
  }
}

object Bakery {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val k=arr(2)

    val graph=Array.fill[Int](n,n)(Int.MaxValue)

    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt)
      graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))
      graph(edge(1)-1)(edge(0)-1)=math.min(graph(edge(1)-1)(edge(0)-1),edge(2))
    }
    var stgVertex:Array[Int]=null
    if(k>0) {
      stgVertex =in.readLine().split(" ").map(_.toInt - 1)
    }
    else {
      println("-1")
      return
    }
    var minDis=Int.MaxValue
    for(j<- 0 until stgVertex.length){
      val i=stgVertex(j)
      if(i!=0 && graph(i)(i-1)!=Int.MaxValue){
        minDis=math.min(graph(i)(i-1),minDis)
      }
      if(i!=graph.length-1 && graph(i)(i+1)!=Int.MaxValue){
        minDis=math.min(graph(i)(i+1),minDis)
      }
    }

    println(if(minDis==Int.MaxValue) "-1" else minDis)
  }
}

object Bakery {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val k=arr(2)

    val graph=Array.fill[Int](n,n)(Int.MaxValue)

    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt)
      graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))
    }
    var stgVertex:Array[Int]=null
    if(k>0) {
      stgVertex =in.readLine().split(" ").map(_.toInt - 1)
    }
    else {
      println("-1")
      return
    }
    var minDis=Int.MaxValue
    for(j<- 0 until stgVertex.length){
      val i=stgVertex(j)
      if(i!=0 && graph(i)(i-1)!=Int.MaxValue){
        minDis=math.min(graph(i)(i-1),minDis)
      }
      if(i!=graph.length-1 && graph(i)(i+1)!=Int.MaxValue){
        minDis=math.min(graph(i)(i+1),minDis)
      }
    }

    println(if(minDis==Int.MaxValue) "-1" else minDis)
  }
}

import scala.collection.mutable._

object Bakery {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val k=arr(2)

    val graph=Array.fill[Int](n,n)(Int.MaxValue)
    for(i<- 0 until n){
      graph(i)(i)=0
    }
    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt)
      graph(edge(0)-1)(edge(1)-1)=edge(2)
    }
    var stgVertex:HashSet[Int]=HashSet[Int]()
    if(m>0)
      in.readLine().split(" ").map(_.toInt-1).foreach(stgVertex+=_)
    else {
      println("-1")
      return
    }
    var minDis=Int.MaxValue
    for (k <- 0 until n) {
      for (i <- 0 until n) {
        for (j <- 0 until n) {
          if (graph(i)(k) != Int.MaxValue && graph(k)(j) != Int.MaxValue)
            graph(i)(j) = math.min(graph(i)(j), graph(i)(k) + graph(k)(j))
            if((stgVertex.contains(i) || stgVertex.contains(j)) && (!stgVertex.contains(i) || !stgVertex.contains(j))){
              minDis=math.min(minDis,graph(i)(j))
            }
        }
      }
    }
    println(if(minDis==Int.MaxValue) "-1" else minDis)
  }
}

object Bakery {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val k=arr(2)

    val graph=Array.fill[Int](n,n)(Int.MaxValue)

    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt)
      graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))
      graph(edge(1)-1)(edge(0)-1)=math.min(graph(edge(1)-1)(edge(0)-1),edge(2))
    }
    var stgVertex:Array[Int]=null
    if(k>0) {
      stgVertex =in.readLine().split(" ").map(_.toInt - 1)
    }
    else {
      println("-1")
      return
    }
    var minDis=Int.MaxValue
    for(k<- 0 until stgVertex.length){
      val i=stgVertex(k)
      for(j<- 0 until graph(0).length) {
        minDis = math.min(graph(i)(j), minDis)
      }
    }
    println(if(minDis==Int.MaxValue) "-1" else minDis)
  }
}

object Bakery {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val k=arr(2)

    val graph=Array.fill[Int](n,n)(Int.MaxValue)

    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt)
      graph(edge(0)-1)(edge(1)-1)=math.min(graph(edge(0)-1)(edge(1)-1),edge(2))
    }
    var stgVertex:Array[Int]=null
    if(k>0) {
      stgVertex =in.readLine().split(" ").map(_.toInt - 1)
    }
    else {
      println("-1")
      return
    }
    var minDis=Int.MaxValue
    for(i<- 0 until stgVertex.length){
      if(i!=0){
        minDis=math.min(graph(i)(i-1),minDis)
      }
      if(i!=graph.length-1){
        minDis=math.min(graph(i)(i+1),minDis)
      }
    }

    println(if(minDis==Int.MaxValue) "-1" else minDis)
  }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object B_368 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa2)
//    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line = readLine
    val nCities = line.int
    val mRoads = line.int
    val kStorages = line.int

    val roadMap = scala.collection.mutable.Map[Int, List[Road]]()
    val city = new Array[Boolean](nCities)

    for (i <- 0 until mRoads) {
      val rLine = readLine()
      val city1 = rLine.int
      val city2 = rLine.int
      val road = new Road(city1, city2, rLine.long)
      val nList1 = roadMap.getOrElse(city1, List())
      roadMap.put(city1, road :: nList1)
      val nList2 = roadMap.getOrElse(city2, List())
      roadMap.put(city2, road :: nList2)
    }

    var res = -1l
    if (kStorages > 0) {
      val sLine = readLine
      val set = scala.collection.mutable.Set[Int]()
      for (i <- 0 until kStorages) {
        set.add(sLine.int)
      }
      for (stor <- set) {
        roadMap.get(stor) match {
          case Some(cityRoads) => for (road <- cityRoads) {
            if (!set.contains(road.city2) && (res == -1 || road.length < res)) {
              res = road.length
            }
          }
          case _ =>
        }
      }
    }

    //---------------------------- parameters reading :end

    outLn(res+"")
    finish
  }

//  class City(num:Int) {
//    var adj = List[
//  }

  class Road(val city1: Int, val city2: Int, val length: Long)

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
"""

val sa2 = """
"""

val sa3 = """
"""
}

}


Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $$$a$$$ minutes to feel refreshed.Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in $$$b$$$ minutes.Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $$$a$$$ minutes in total, then he sets his alarm to go off in $$$c$$$ minutes after it is reset and spends $$$d$$$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $$$c$$$ minutes and tries to fall asleep for $$$d$$$ minutes again.You just want to find out when will Polycarp get out of his bed or report that it will never happen.Please check out the notes for some explanations of the example.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The only line of each testcase contains four integers $$$a, b, c, d$$$ ($$$1 \le a, b, c, d \le 10^9$$$) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.

For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.

NoteIn the first testcase Polycarp wakes up after $$$3$$$ minutes. He only rested for $$$3$$$ minutes out of $$$10$$$ minutes he needed. So after that he sets his alarm to go off in $$$6$$$ minutes and spends $$$4$$$ minutes falling asleep. Thus, he rests for $$$2$$$ more minutes, totaling in $$$3+2=5$$$ minutes of sleep. Then he repeats the procedure three more times and ends up with $$$11$$$ minutes of sleep. Finally, he gets out of his bed. He spent $$$3$$$ minutes before the first alarm and then reset his alarm four times. The answer is $$$3+4 \cdot 6 = 27$$$.The second example is almost like the first one but Polycarp needs $$$11$$$ minutes of sleep instead of $$$10$$$. However, that changes nothing because he gets $$$11$$$ minutes with these alarm parameters anyway.In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is $$$b=9$$$.In the fourth testcase Polycarp wakes up after $$$5$$$ minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(

object CodeforcesRoundE87a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    var Array(a, b, c, d) = rll_int
    var inBed = b
    val res =
      if (inBed >= a) {
        inBed
      } else {
        if (c <= d) {
          -1
        } else {
          val n = Math.ceil((a.toDouble - inBed) / (c - d)).toLong
          inBed + n * c
        }
      }
    writer.println(res)
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CE87A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class CE87A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t= ni()
    REP(t) { _ =>
      val a = ni()
      val b = ni()
      val c = ni()
      val d = ni()

      if(b >= a) {
        out.println(b)
      } else if (d >= c) {
        out.println(-1)
      } else {
        val left = a - b
        val x = b.toLong
        val sleepx = c - d
        val m = Math.ceil(left / sleepx.toDouble).toLong
        out.println(x + m * c)
      }
    }
  }
}

object ProblemF extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val a = in.nextInt()
    val b = in.nextInt()
    val c: Int = in.nextInt()
    val d = in.nextInt()

    val res = if (b >= a){
      b
    } else if (c - d > 0) {
      val left = math.max(0, a - b).toLong
      val count = left / (c - d) + (if (left % (c - d) > 0) 1 else 0)
       count * c + b
    } else {
      -1
    }

    println(res)
  }

}


A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.

The first input line contains two integers n and k (1 ≤ n ≤ 5·105; 2 ≤ k ≤ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.

Print a single integer — the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.

import java.util.StringTokenizer

object _219C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt
  val s = " " + next
  val f = Array.fill(n + 1, k)(0)
  var min = 0
  var minmin = 1
  for (i <- 1 to n) {
    for (j <- 0 until k) {
      val delta = if (j == s(i) - 'A') 0 else 1
      if (j != min) f(i)(j) = f(i - 1)(min) + delta
      else f(i)(j) = f(i - 1)(minmin) + delta
    }
    min = if (f(i)(0) < f(i)(1)) 0 else 1
    minmin = 1 - min
    for (j <- 2 until k)
      if (f(i)(j) < f(i)(min)) {
        minmin = min
        min = j
      } else if (f(i)(j) < f(i)(minmin)) minmin = j
  }
  var ii = n
  var jj = 0
  for (j <- 0 until k)
    if (f(n)(j) < f(n)(jj)) jj = j

  println(f(ii)(jj))
  val builder = new StringBuilder
  while (ii > 0) {
    builder += ('A' + jj).toChar
    val delta = if (s(ii) - 'A' == jj) 0 else 1
    var newJJ = 0
    for (j <- 0 until k)
      if (j != jj && f(ii - 1)(j) + delta == f(ii)(jj)) newJJ = j
    jj = newJJ
    ii = ii - 1
  }
  println(builder.result.reverse)
//  f.foreach(i => println(i.toList))
}

import java.util.Scanner

object Program {
	def main(args:Array[String]) = {
		val in = new Scanner(System.in)
		val (n, k) = (in.nextInt(), in.nextInt())
		val cols = (in.next()).toCharArray

		if(k == 2){
			var ans = Int.MaxValue
			var sol = Array[Char]()
			for(t <- Array("AB", "BA")){
				var p = 0
				var s = new Array[Char](n)
				for(i <- 0 until cols.length){
					s(i) = t(i&1)
					if(cols(i)!=t(i&1))p+=1
				}
				if(p < ans) {
					ans = p
					sol = s
				}
			}
			println(ans)
			for(c <- sol)print(c)
			println()
		} else {
			var ans = 0

			for(i <- 1 to n - 1){
				if(cols(i) == cols(i-1)){
					ans += 1
					var c =0
					if((i + 1 < n && cols(i+1) == 'A') || cols(i-1) == 'A') c += 1
					if((i + 1 < n && cols(i+1) == (c+'A')) || cols(i-1) == (c+'A')) c += 1
					cols(i)=(c+'A').toChar
				}
			}
			println(ans)
			for(c <- cols) print(c)
			println()
		}
	}
}

object test5 extends App {
	val Array(n,k)=readLine.split(" ").map(_.toInt)
	val arr=readLine.toCharArray()
	var count=0
	val ans=k match{
		case 2=>countTwo
		case _=>countThree
	}

	println(count)
	println(ans)

	def countTwo={
	    val str1="AB"*(n/2)+"A"*(n%2)
	    val str2="BA"*(n/2)+"B"*(n%2)

	    var count1=0
	    var count2=0

	    for(i<-0 until n)
	    	if(arr(i)!=str1(i)) count1+=1 else count2+=1

	    count=math.min(count1,count2)
	    if(count1<count2) str1 else str2
	}

	def countThree={
	    for(i<-1 until n if arr(i)==arr(i-1)){
    		count+=1
    		val c='A' to 'Z' find(c=>c!=arr(i-1) && (i==n-1 || c!=arr(i+1)))
    		arr(i)=c.get
	    }
	    arr.mkString
	}

}

import java.util.StringTokenizer

object _219C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt
  val s = " " + next
  val f = Array.fill(n + 1, k)(0)
  var min = 0
  var minmin = 1
  for (i <- 1 to n) {
    for (j <- 0 until k) {
      val delta = if (j == s(i) - 'A') 0 else 1
      if (j != min) f(i)(j) = f(i - 1)(min) + delta
      else f(i)(j) = f(i - 1)(minmin) + delta
    }
    min = 0
    minmin = 1
    for (j <- 2 until k)
      if (f(i)(j) < f(i)(min)) {
        minmin = min
        min = j
      } else if (f(i)(j) < f(i)(minmin)) minmin = j
  }
  var ii = n
  var jj = 0
  for (j <- 0 until k)
    if (f(n)(j) < f(n)(jj)) jj = j

  println(f(ii)(jj))
  val builder = new StringBuilder
  while (ii > 0) {
    builder += ('A' + jj).toChar
    val delta = if (s(ii) - 'A' == jj) 0 else 1
    var newJJ = 0
    for (j <- 0 until k)
      if (j != jj && f(ii - 1)(j) + delta == f(ii)(jj)) newJJ = j
    jj = newJJ
    ii = ii - 1
  }
  println(builder.result.reverse)
  //  f.foreach(i => println(i.toList))
}

import java.util.Scanner

object Program {
	def main(args:Array[String]) = {
		val in = new Scanner(System.in)
		val (n, k) = (in.nextInt(), in.nextInt())
		val cols = in.next()
		var moves = Array.ofDim[Int](26, n + 1)
		var sol = Array.ofDim[Int](26, n + 1)
		for(c <- 'A' to 'Z') moves(c - 'A')(n) = 0
		for(i <- n - 1 to 0 by -1; c <- 0 until k){
			if (c != (cols(i)-'A').toInt) {
				moves(c)(i) = moves(cols(i)-'A')(i + 1)
				sol(c)(i) = cols(i)-'A'
			}
			else {
				var ans = Int.MaxValue
				for(c2 <- 0 until k){
					if (c2 != c && ans > moves(c2)(i + 1) + 1){
						ans = moves(c2)(i+1)+1
						sol(c)(i) = c2
					}
				}
				moves(c)(i) = ans
			}
		}
		var c = if (cols(0) == 'A') 1 else 0
		println(moves(c)(0))
		for(i <- 0 until n){
			print((sol(c)(i)+'A').toChar)
			c = sol(c)(i)
		}
		println()
	}
}

import java.util.Scanner

object Program {
	def main(args:Array[String]) = {
		val in = new Scanner(System.in)
		val (n, k) = (in.nextInt(), in.nextInt())
		val cols = in.next().toCharArray
		if(k == 2){
			var ans = Int.MaxValue
			var sol = ""
			for(t <- Array("AB", "BA")){
				var p = 0
				var s = ""
				for(i <- 0 until cols.length){
					s += t(i&1)
					if(cols(i)!=t(i&1))p+=1
				}
				if(p < ans) ans = p; sol = s
			}
			println(ans)
			println(sol)
		} else {
			var ans = 0
			for(i <- 0 until n - 1){
				if(cols(i) == cols(i+1)){
					ans += 1
					for(c <- 0 until k)
						if(cols(i+1) != c+'A'){
							if(i > 0)if(cols(i-1) != c+'A'){
								cols(i) = (c+'A').toChar
							}
						}
				}
			}
			println(ans)
			var s = ""
			for(c <- cols) s += c
			println(s)
		}
	}
}

import java.util.Scanner

object Program {
	def main(args:Array[String]) = {
		val in = new Scanner(System.in)
		val (n, k) = (in.nextInt(), in.nextInt())
		val cols = in.next().toCharArray
		if(k == 2){
			var ans = Int.MaxValue
			var sol = ""
			for(t <- Array("AB", "BA")){
				var p = 0
				var s = ""
				for(i <- 0 until cols.length){
					s += t(i&1)
					if(cols(i)!=t(i&1))p+=1
				}
				if(p < ans) {
					ans = p
					sol = s
				}
			}
			println(ans)
			println(sol)
		} else {
			var ans = 0
			for(i <- 0 until n - 1){
				if(cols(i) == cols(i+1)){
					ans += 1
					for(c <- 0 until k)
						if(cols(i+1) != c+'A'){
							if(i > 0)if(cols(i-1) != c+'A'){
								cols(i) = (c+'A').toChar
							}
						}
				}
			}
			println(ans)
			var s = ""
			for(c <- cols) s += c
			println(s)
		}
	}
}

import java.util.Scanner

object Program {
	def main(args:Array[String]) = {
		val in = new Scanner(System.in)
		val (n, k) = (in.nextInt(), in.nextInt())
		val cols = in.next().toCharArray
		if(k == 2){
			var ans = Int.MaxValue
			var sol = ""
			for(t <- Array("AB", "BA")){
				var p = 0
				var s = ""
				for(i <- 0 until cols.length){
					s += t(i&1)
					if(cols(i)!=t(i&1))p+=1
				}
				if(p < ans) {
					ans = p
					sol = s
				}
			}
			println(ans)
			println(sol)
		} else {
			var ans = 0
			for(i <- 1 until n - 1){
				if(cols(i) == cols(i-1)){
					ans += 1
					var c = 0
					if(cols(i+1) == 'A' || cols(i-1) == 'A') c += 1
					if(cols(i+1) == (c+'A') || cols(i-1) == (c+'A')) c += 1
					cols(i) = (c+'A').toChar
				}
			}
			println(ans)
			var s = ""
			for(c <- cols) s += c
			println(s)
		}
	}
}

object test5 extends App {
	val Array(n,k)=readLine.split(" ").map(_.toInt)
	val arr=readLine.toCharArray()
	var count=0
	k match{
		case 2=>countTwo
		case _=>countThree
	}

	println(count)
	println(arr.mkString)

	def countTwo={
		for(i<-1 until n if arr(i)==arr(i-1)){
			count+=1
    		val c='A' to 'Z' find(c=>c!=arr(i-1))
            arr(i)=c.get
		}
	}

	def countThree={
	    for(i<-1 until n if arr(i)==arr(i-1)){
    		count+=1
    		val c='A' to 'Z' find(c=>c!=arr(i-1) && (i==n-1 || c!=arr(i+1)))
    		arr(i)=c.get
	    }
	}

}


A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles.In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.Each boy can rent at most one bike, one cannot give his bike to somebody else.What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?

The first line of the input contains three integers n, m and a (1 ≤ n, m ≤ 105; 0 ≤ a ≤ 109). The second line contains the sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104), where bi is the amount of the i-th boy's personal money. The third line contains the sequence of integers p1, p2, ..., pm (1 ≤ pj ≤ 109), where pj is the price for renting the j-th bike.

Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r = s = 0.

NoteIn the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Long] = {
    val N, M = sc.nextInt
    val A: Long = sc.nextLong
    val B: Array[Long] = Array.fill(N)(sc.nextLong).sorted
    val P: Array[Long] = Array.fill(M)(sc.nextLong).sorted

    def simulate(n: Int): Long = {

      @tailrec
      def loop(acc: Long, i: Int): Long = {
        if (i == n) acc
        else loop(acc + (0L max (P(i) - B(N - n + i))), i + 1)
      }

      loop(0L, 0)
    }

    @tailrec
    def binSearch(a: Int, b: Int): Int = {
      val m = (a + b) / 2
      if (b - a <= 1) a
      else if (simulate(m) > A) binSearch(a, m)
      else binSearch(m, b)
    }

    val nm = N min M
    val r = if (simulate(nm) <= A) nm
            else binSearch(0, nm)
    if (r == 0) List(0, 0)
    else List(r, (P.take(r).sum - A) max 0)
  }

  out.println(solve.mkString(" "))
  out.close
}

import scala.math._
import java.util.Scanner

object RentingBikes extends App {
	val scan = new Scanner(System.in)
	val n = scan.nextInt
	val m = scan.nextInt
	val a = scan.nextInt

	val b = {
		for(i <- 0 until n) yield scan.nextInt
	}.toArray.sortWith((x, y) => x < y)

	val p = {
		for(i <- 0 until m) yield scan.nextInt
	}.toArray.sortWith((x, y) => x < y)

	def calc(x: Int): Long = {
		var sum: Long = 0
		for(i <- 0 until x if p(i) > b(i + b.size - x)) {
			sum = sum - b(i + b.size - x) + p(i)
		}
		sum
	}

	var high = min(n, m) + 1
	var low = 1
	while (high > low) {
		val mid = (high + low) / 2
		calc(mid) <= a match {
			case true => low = mid + 1
			case false => high = mid
		}
	}

	val ret = low - 1
	var sum = -a
	for(i <- 0 until ret) sum = sum + p(i)
	sum = max(sum, 0)
	println("%d %d".format(ret, sum))

}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Int] = {
    val N, M = sc.nextInt
    val A: Int = sc.nextInt
    val B: List[Int] = List.fill(N)(sc.nextInt).sortWith(_ > _)
    val P: List[Int] = List.fill(M)(sc.nextInt).sortWith(_ < _)

    def simulate(n: Int): Int = {
      (P.take(n), B.take(n)).zipped.map { (a: Int , b: Int) =>
        (a - b) max 0
      }.sum
    }

    @tailrec
    def binSearch(a: Int, b: Int): Int = {
      val c = (a + b) / 2
      val r= simulate(c)
      if (b == c) a
      else if (A <= r) binSearch(a, c)
      else binSearch(c + 1, b)
    }

    val r = binSearch(0, N)
    val s = (P.take(r).sum - A) max 0
    List(r, s)
  }

  out.println(solve.mkString(" "))
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  // N planks
  // H_i ... hight of the ith plank
  // K consecutive planks to be removed

  def solve(): Long = {
    val N, K = sc.nextInt
    val dp: Array[Long] = Array.fill(N + 1)(0)

    1 to N foreach { i =>
      dp(i) = dp(i - 1) + sc.nextLong
    }

    var min: Long = Long.MaxValue
    var j: Int = 0
    1 to (N - K + 1) foreach { i =>
      val kSum = dp(i + K - 1) - dp(i - 1)
      if (kSum < min) {
        min = kSum
        j = i
      }
    }
    j
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Int] = {
    val N, M = sc.nextInt
    val A: Int = sc.nextInt
    val B: List[Int] = List.fill(N)(sc.nextInt).sortWith(_ > _)
    val P: List[Int] = List.fill(M)(sc.nextInt).sortWith(_ < _)

    def simulate(n: Int): Int = {
      (P.take(n).reverse, B.take(n)).zipped.map { (a: Int , b: Int) =>
        (a - b) max 0
      }.sum
    }

    @tailrec
    def binSearch(a: Int, b: Int): Int = {
      val m = (a + b) / 2
      if (b - a <= 1) a
      else if (simulate(m) > A) binSearch(a, m)
      else binSearch(m, b)
    }

    val nm = N min M
    val r = if (simulate(nm) <= A) nm
            else binSearch(0, nm)
    if (r == 0) List(0, 0)
    else List(r, (P.take(r).sum - A) max 0)
  }

  out.println(solve.mkString(" "))
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Int] = {
    val N, M = sc.nextInt
    val A: Int = sc.nextInt
    val B: List[Int] = List.fill(N)(sc.nextInt).sortWith(_ > _)
    val P: List[Int] = List.fill(M)(sc.nextInt).sortWith(_ < _)

    def simulate(n: Int): Int = {
      (P.take(n).reverse, B.take(n)).zipped.map { (a: Int , b: Int) =>
        (a - b) max 0
      }.sum
    }

    @tailrec
    def binSearch(a: Int, b: Int): Int = {
      val m = (a + b) / 2
      if (b - a <= 1) a
      else if (simulate(m) > A) binSearch(a, m)
      else binSearch(m, b)
    }

    val nm = N min M
    val r = if (simulate(nm) <= A) nm
            else binSearch(0, nm)
    if (r == 0) List(0, 0)
    else List(r, P.take(r).sum - A)
  }

  out.println(solve.mkString(" "))
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Int] = {
    val N, M = sc.nextInt
    val A: Int = sc.nextInt
    val B: List[Int] = List.fill(N)(sc.nextInt).sortWith(_ > _)
    val P: List[Int] = List.fill(M)(sc.nextInt).sortWith(_ < _)

    def simulate(n: Int): Int = {
      (P.take(n), B.take(n)).zipped.map { (a: Int , b: Int) =>
        (a - b) max 0
      }.sum
    }

    @tailrec
    def binSearch(a: Int, b: Int): Int = {
      val c = (a + b) / 2
      val r= simulate(c)
      if (b == c) a
      else if (A <= r) binSearch(a, c)
      else binSearch(c + 1, b)
    }

    val r = binSearch(0, N min M)
    val s = (P.take(r).sum - A) max 0
    List(r, s)
  }

  out.println(solve.mkString(" "))
  out.close
}


Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a group of b-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.You're given a string s. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.

The only line contains s (1 ≤ |s| ≤ 105) consisting of lowercase latin letters.

Print «Yes» if the string can be split according to the criteria above or «No» otherwise. Each letter can be printed in arbitrary case.

NoteIn sample case two zzcxx can be split into subsequences zc and zxx each of which is adorable.There's no suitable partition in sample case three.

import scala.collection.mutable

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))
    def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val s = readString()
        var f = new mutable.HashMap[Char, Int]()

        s.foreach(c => f.get(c) match {
            case Some(x) => f += c -> (x + 1)
            case None => f += c -> 1
        })

        if (f.size > 4 || f.size < 2) {
            print("No")
            return
        }

        if (f.size == 4) {
            print("Yes")
            return
        }

        if (f.size == 3)
            if (f.exists(p => p._2 > 1)) {
                print("Yes")
                return
            } else {
                    print("No")
                    return
                }

        if (f.size == 2)
            if (f.exists(p => p._2 < 2)) {
                print("No")
                return
            } else {
                print("Yes")
                return
            }
    }
}

import scala.collection.mutable

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))
    def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        /*val Array(hh, mm) = readInt()
        val Array(h, d, c, n) = readInt().map(_.toFloat)

        var price = 0.0
        if (hh >= 20) price = Math.ceil(h / n) * c * 0.8
        else price = Math.min(Math.ceil(h / n) * c, Math.ceil(h + ((20 - hh - 1)*60 + 60 - mm)*d / n) * c * 0.8)

        print("%.4f".format(price))*/

        val s = readString()
        val s1 = new mutable.HashSet[Char]()
        val s2 = new mutable.HashSet[Char]()
        val f1 = new Array[Int](s.length)
        val f2 = new Array[Int](s.length)

        for (i <- 0 until s.length) {
            s1 += s(i)
            f1(i) = s1.size
        }

        for (i <- s.length - 1 to 0 by -1) {
            s2 += s(i)
            f2(i) = s2.size
        }

        for (i <- 0 until s.length - 1)
            if (f1(i) == f2(i + 1) && f1(i) == 2) {
                print("Yes")
                return
            }
        print("No")
    }
}

import scala.collection.mutable

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))
    def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        /*val Array(hh, mm) = readInt()
        val Array(h, d, c, n) = readInt().map(_.toFloat)

        var price = 0.0
        if (hh >= 20) price = Math.ceil(h / n) * c * 0.8
        else price = Math.min(Math.ceil(h / n) * c, Math.ceil(h + ((20 - hh - 1)*60 + 60 - mm)*d / n) * c * 0.8)

        print("%.4f".format(price))*/

        val s = readString()
        val s1 = new mutable.HashSet[Char]()
        val s2 = new mutable.HashSet[Char]()
        val f1 = new Array[Int](s.length)
        val f2 = new Array[Int](s.length)

        for (i <- 0 until s.length) {
            s1 += s(i)
            f1(i) = s1.size
        }

        for (i <- s.length - 1 to 0 by -1) {
            s2 += s(i)
            f2(i) = s2.size
        }

        for (i <- 0 until s.length)
            if (f1(i) == f2(i) && f1(i) == 2) {
                print("Yes")
                return
            }
        print("No")
    }
}


Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.

The first line contains the single number d — the maximum number of the day that Vasya's clock can show (1 ≤ d ≤ 106). The second line contains a single integer n — the number of months in the year (1 ≤ n ≤ 2000). The third line contains n space-separated integers: ai (1 ≤ ai ≤ d) — the number of days in each month in the order in which they follow, starting from the first one.

Print a single number — the number of times Vasya manually increased the day number by one throughout the last year.

NoteIn the first sample the situation is like this:   Day 1. Month 1. The clock shows 1. Vasya changes nothing.  Day 2. Month 1. The clock shows 2. Vasya changes nothing.  Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1.  Day 2. Month 2. The clock shows 2. Vasya changes nothing.  In total, Vasya manually changed the day number by 1 exactly 2 times.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val d = in.next().toInt
  val n = in.next().toInt
  println(in.next().split(' ').init.map(d - _.toInt).sum)
}

object Main {
  def main(args: Array[String]) {
    val d = readInt()
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    println(a.dropRight(1).map(d -).sum)
  }
}


Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO.

Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.

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)
  val s = readLine.toCharArray

  var cnt = 0

  var prev = ' '
  var same3 = false
  var same2 = 0
  for (i <- 0 until n) {
    if (s(i) != prev) cnt += 1
    prev = s(i)
    if (i > 1 && s(i) == s(i - 1) && s(i) == s(i - 2)) same3 = true
    if (i > 2 && s(i) == s(i - 1) && s(i - 3) == s(i - 2)) same3 = true
    if (i > 0 && s(i) == s(i - 1)) same2 += 1
  }

  if (same3 || same2 > 1) cnt += 2
  else if (n > 1) {
    if (s(0) == s(1) || s(n - 1) == s(n - 2) || same2 > 0) cnt += 1
  }

  println(cnt)
}

object C{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val s=nextString
    var sum=1
    var nn=0

    for(i<-0 until n-1){
      if(s(i)==s(i+1)){
        nn+=1
      }else{
        sum+=1
      }
    }
    if(nn==1){
      sum+=1
    }else if(nn>=2){
      sum+=2
    }
    out.println(sum)

    //code ends here
    out.flush
    out.close
  }
}

import scala.io.Source

/**
  * Created by Xiao on 2016/3/15 0015.
  */

object me {
    def main(args: Array[String]): Unit = {
        val line = Source.stdin.getLines()
        val n = Integer.parseInt(line.next())
        val str = line.next()
        var ans = 1
        var i = 0
        for(i <- 1 to n-1) {
            if(str.charAt(i) != str.charAt(i-1)) {
                ans+=1
            }
        }
        ans+=2
        if(n<ans) {
            ans = n
        }
        println(ans)
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()

  def count(str: String): Int = {
    str.tail.foldLeft(str.head, 1) {
      case ((el1, count), el2) if el1 == el2 => (el2, count)
      case ((el1, count), el2) => (el2, count + 1)
    }._2
  }

  println(line.sliding(2).count(a => a.length == 2 && a.head == a.last) match {
    case 0 => count(line)
    case 1 => count(line) + 1
    case _ => count(line) + 2
  })

}

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)
  val s = readLine.toCharArray

  var cnt = 0

  var prev = ' '
  var same3 = false
  for (i <- 0 until n) {
    if (s(i) != prev) cnt += 1
    prev = s(i)
    if (i > 1 && s(i) == s(i - 1) && s(i) == s(i - 2)) same3 = true
  }

  if (same3) cnt += 2
  else if (n > 1) {
    if (s(0) == s(1) || s(n - 1) == s(n - 2)) cnt += 1
  }

  println(cnt)
}

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)
  val s = readLine.toCharArray

  var cnt = 0

  var prev = ' '
  var same3 = false
  for (i <- 0 until n) {
    if (s(i) != prev) cnt += 1
    prev = s(i)
    if (i > 1 && s(i) == s(i - 1) && s(i) == s(i - 2)) same3 = true
    if (i > 2 && s(i) == s(i - 1) && s(i - 3) == s(i - 2)) same3 = true
  }

  if (same3) cnt += 2
  else if (n > 1) {
    if (s(0) == s(1) || s(n - 1) == s(n - 2)) cnt += 1
  }

  println(cnt)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()

  def count(str: String): Int = {
    str.tail.foldLeft(str.head, 1) {
      case ((el1, count), el2) if el1 == el2 => (el2, count)
      case ((el1, count), el2) => (el2, count + 1)
    }._2
  }

  println(line.sliding(2).count(a => a.head == a.last) match {
    case 0 => count(line)
    case 1 => count(line) + 1
    case _ => count(line) + 2
  })

}