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

object Solution {
    val reader = new Scanner(System.in)
    val writer =  new PrintWriter(System.out)

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

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

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val x = reader.nextLong()
        val y = reader.nextLong()
        val c = reader.nextLong()

        val (a,b) = if (x > y) (x,y) else (y,x)

        val sub = a - b
        if (c > sub * 2 || sub * 2 < a)
            writer.println(-1)
        else if (c > sub)
            writer.println(c - sub)
        else
            writer.println(c + sub)
    }

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

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

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if ((a max b max c) > n) -1
      else d

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c < l) c + l else c - l

    val ans =
      if ((a max b max c) > n) -1
      else d

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x, y, c) = readLine().split(" ").map(_.toInt)
    val (a, b)         = (x min y, x max y)

    val l = b - a
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans = if (b > n || a > l || n - b != l - a || d > n || d == a || d == b) -1 else d

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x, y, c) = readLine().split(" ").map(_.toInt)
    val (a, b)         = (x min y, x max y)

    val l = b - a
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans = if (b > n || a > l || n - b != l - a || d > n) -1 else d

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if (
        a.min(b) <= l + 1 && l + 1 <= a.max(b) && a.max(b) <= n &&
        d <= n && d != a && d != b &&
        c % l == d % l && a % l == b % l
      ) d
      else -1

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if (a.min(b) <= l + 1 && l + 1 <= a.max(b) && a.max(b) <= n && d <= n && d != a && d != b) d
      else -1

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if (a.min(b) <= l + 1 && a.max(b) <= n && d <= n) d
      else -1

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if (a.max(b) > n || d > n || d < 1) -1
      else d

    println(ans)
  }
}


import java.util.Scanner

object Matrix extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()

  val mat = Array.ofDim[Int](n, n)
  val t = if (n % 2 == 1) n else n - 1

  for {
    i <- 0 until n - 1
    j <- 0 until n
  } {
    mat(i)(j) = 1 + (i + j) % t
    if (j == n - 1) {
      mat(i)(j) = mat(i)(i)
      mat(j)(i) = mat(i)(i)
      mat(i)(i) = 0
    }
  }

  for {
    i <- 0 until n
  } {
    println(mat(i).mkString(" "))
  }

}

import java.util.Scanner

object Matrix extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()

  val mat = Array.ofDim[Int](n, n)

  for {
    i <- 0 until n - 1
    j <- 0 until n
  } {
    mat(i)(j) = 1 + (i + j) % (n)
    if (j == n - 1) {
      mat(i)(j) = mat(i)(i)
      mat(j)(i) = mat(i)(i)
      mat(i)(i) = 0
    }
  }

  for {
    i <- 0 until n
  } {
    println(mat(i).mkString(" "))
  }

}


import java.util.StringTokenizer

object _401 extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val x = next.toInt
  val sum = (1 to n).map(i => next.toInt).sum.abs
  println((sum + x - 1) / x)
}

object HelloWorld {
    def main(args: Array[String]) {
        val l = Console.readLine().split(" ").map(i => Integer.parseInt(i))
        val n = l(0)
        val x = l(1)
        var psum = Console.readLine().split(" ").map(i => Integer.parseInt(i)).reduce(_ + _)
        val res = math.abs(psum)/x + (if (psum%x == 0) 0 else 1)

        println(res)
    }
}

object Vanya {
  def process(n: Int, x:Int, cards: Array[Int]): Int = {
    val value:Int = Math.abs(cards.reduce(_+_))
    val div = value/x
    if(value%x == 0 ) div
    else div + 1
  }
  def main(args:Array[String]) = {
    val Inputs:List[Int] = scala.io.Source.stdin.getLines().
      grouped(2).toList.
      map((y:Seq[String]) => {
        val yl = y.toList
        val Array(n:Int, x:Int) = yl(0).split(" ").map(_.toInt);
        val cards:Array[Int] = yl(1).split(" ").map(_.toInt)
        process(n, x, cards);
    })
    Inputs.foreach((x: Int)=> println(x))
  }
}

import scala.collection.mutable
import scala.io._
import scala.math._
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object a6 {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().toArray
    val x = lines(0).split(' ')(1).toInt
    var r = lines(1).split(' ').map(_.toInt).sum.abs
    var count=0
    for {i <- (1 to x).reverse} {
      if (r >= i) {
        count += r/i
        r%=i
      }
    }
    println(count)
  }
}

object Solution extends App {
  val Array(n, x) = readLine().split(" ").map(_.toInt)
  val data = Math.abs(readLine().split(" ").map(_.toInt).sum)
  val r = if (data % x > 0) 1 else 0
  println(data / x + r)
}

object A401 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = readInts(2)
    val in = math.abs(readInts(n).sum)
    println((in+x-1)/x)
  }

  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 java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P401A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, X = sc.nextInt

  def solve(): Unit = {
    val balance = List.fill(N)(sc.nextInt).sum.abs
    val answer = if (balance % X > 0) balance / X + 1
                 else balance / X
    out.println(answer)
  }

  solve
  out.close
}

import java.util.Scanner

/**
 * Created by hama_du on 2014/03/11.
 */
object ProblemA extends App {
  val in = new Scanner(System.in)
  val n = in.nextInt
  val x = in.nextInt
  val sum = Math.abs((0 until n).map(_ => in.nextInt).sum)
  println((sum + x - 1) / x)
}

import java.util.Scanner

object CF401A extends App {
    val in = new Scanner(System.in)
    val n = in.nextInt
    val x = in.nextInt
    val sum = Math.abs((0 until n).map(_ => in.nextInt).sum)
    val answer = (sum + x - 1) / x;
    println(answer)
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by Kuang.Ru on 14-9-18.
 */
object A401 extends App{
  val sc = new Scanner(System.in)
  val n, x = sc.nextInt()
  val founded = new ArrayBuffer[Int]()
  var i = 0

  while (i < n) {
    founded += sc.nextInt()
    i += 1
  }

  val diff = Math.abs(founded.sum) - 0

  println(if (diff % x == 0){
    diff / x
  } else {
    diff / x + 1
  })
}

object A extends App {
  val sc = new java.util.Scanner(System.in)
  val n, x = sc.nextInt()
  val in = Array.fill(n)(sc.nextInt())
  val sum = in.sum
  println((sum/x).abs + (if (sum%x==0) 0 else 1))
}

object main extends App with fastIO {

  var Array(n, x) = readLine split(" ") map(_.toInt)
  println((readLine.split(" ").map(_.toInt).sum.abs + x - 1) / x)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

import scala.collection.mutable
import scala.io._
import scala.math._
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object a6 {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().toArray
    val cards = lines(1).split(' ').map(_.toInt)
    val h = new mutable.HashMap[Int, Int]()
    val s = new mutable.HashSet[Int]()
    (-1000 to 1000).foreach(h(_)=0)
    cards.foreach(a=>{h(a)=h(a)+1;s.add(abs(a))})
    println(s.filter(_>0).map(a=>abs(h(a)-h(-a))).sum)
  }
}

object A extends App {
  val sc = new java.util.Scanner(System.in)
  val n, x = sc.nextInt()
  val in = Array.fill(n)(sc.nextInt())
  val sum = in.sum
  println(sum/x + (if (sum%x==0) 0 else 1))
}


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

  val t = readInt()

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

    println(an.mkString(" "))
  }
}

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

  val t = readInt()

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

    var flags = Array.fill(n + 1)(0)
    val an    = a2n.foldLeft(List.empty[Int])((as, a) => if (flags(a) == 1) as else { flags(a) = 1; a :: as }).reverse

    println(an.mkString(" "))
  }
}

import scala.io.StdIn._

object contest356B extends App {

  def getRear(input: Array[Int]): String= {
    val res = new Array[Int](input.length / 2)
    var found = 0
    for (i <- 0 until input.length) {
      if (!res.contains(input(i))) {
        res(found) = input(i)
        found += 1
      }
    }
    var fin = ""
    res.foreach(x => fin += s"$x ")
    fin.dropRight(1)
  }

  val t = readInt
  var lst: List[String] = List()
  for(a <- 1 to t){
    readLine
    val input :Array[Int] = readLine.split(" ").map(_.toInt)
    lst = getRear(input) :: lst
  }

  for(y <- lst.length-1 to 0 by -1){
    println(lst(y))
  }

}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val known = Array.fill[Set[Int]](n){Set.empty[Int]}
  Range(0, m).foreach { _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    known(a) += b
    known(b) += a
  }
  val r = known.indices.flatMap{ i =>
    known(i).flatMap{j =>
      known(j).intersect(known(i)).map(t => known(i).size + known(j).size + known(t).size)
    }
  }
  if (r.isEmpty)
    println(-1)
  else
    println(r.min - 6)
}

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

object BearMusketeers {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def findMin(g : Map[Int,IndexedSeq[Int]], n: Int) : Int = {
     var curBest = scala.Int.MaxValue
     for (i <- 1 to n) {
       if (g(i).size < curBest) {
         for (j <- g(i).filter { _ > i }) {
           if (g(i).size + g(j).size < curBest) {
             for (k <- g(i).filter{x => x > j && (g(j) contains x) }) {
               if (g(i).size + g(j).size + g(k).size < curBest)
                 curBest = g(i).size + g(j).size + g(k).size
             }
           }
         }
       }
     }
     if (curBest < scala.Int.MaxValue) curBest - 6 else -1
   }

   def main(args: Array[String]) {
     val (n,m) = readTuple
     val abs = for {
       i <- 1 to m
       t = readTuple
     } yield t
     val absSym = abs.flatMap(t => List(t,(t._2,t._1))).groupBy(_._1)
       .mapValues(is => is.map(_._2))
       .filterNot{ _._2.length < 2}

     /* val mins = for {
       i <- absSym.keys
       j <- absSym(i).filter(_ > i)
       k <- absSym(i).filter(k => k  > j )
       if (absSym.getOrElse(j, IndexedSeq[Int]()) contains k)
       //_ =   println(s"$i, $j en $k kennen elkaar size ${(absSym(i).size + absSym(j).size + absSym(k).size)}")

     } yield (absSym(i).size + absSym(j).size + absSym(k).size)
     if (mins.isEmpty) {
       println("-1")
     } else {
       println(mins.min - 6)
     }*/
     println(findMin(absSym.withDefaultValue(IndexedSeq[Int]()), n))
   }

}

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

object BearMusketeers {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val (n,m) = readTuple
     val abs = for {
       i <- 1 to m
       t = readTuple
     } yield t
     val absSym = abs.flatMap(t => List(t,(t._2,t._1))).groupBy(_._1)
       .mapValues(is => is.map(_._2))
       .filterNot{ _._2.length < 3}
     val mins = for {
       i <- absSym.keys
       j <- absSym(i).filter(_ > i)
       k <- absSym(i).filter(k => k  > j )
       if (absSym.getOrElse(j, IndexedSeq[Int]()) contains k)
     } yield (absSym(i).toSet + absSym(j) + absSym(k)).size
     if (mins.isEmpty) {
       println("-1")
     } else {
       println(mins.min - 3)
     }
   }

}


object P1497A extends App {
  import java.io._
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  val t = readInt
  for (_ <- 0 until t) {
    val n = readInt
    val sortedArray = readInts.sorted
    var isVisited = Map[Int, Boolean]()
    var ascending = List[Int]()
    var rest = List[Int]()
    sortedArray.foreach {
      case i@_ if isVisited getOrElse(i, false) => rest = i +: rest
      case i@_ => {
        ascending = i +: ascending
        isVisited += (i -> true)
      }
    }
    ascending = ascending.reverse
    println((ascending ++ rest).mkString(" "))
  }
}

import scala.reflect.ClassTag
import scala.collection.immutable.StringOps
import scala.collection.immutable
object cf1497a {

	def readInt(s: String) = s.toInt
	def readLong(s: String) = s.toLong

  def read[T](conv: (String) => T): T = {
		conv(Console.in.readLine())
	}

	def readArray[T:ClassTag](conv: (String) => T): Array[T] = {
		val line = Console.in.readLine()
		line.split(' ').map(conv(_))
	}

	def solve(arr: Array[Long]): Unit = {
		val s = arr.sorted
		val min = s.foldLeft(0L)( (min, v) => {
			if (v == min) v+1
			else min
		})

		val lessThanUnique = immutable.SortedSet(s.takeWhile(_ < min):_*).toArray
		val reminder = arr.diff(lessThanUnique.toSeq)
		println((lessThanUnique ++ reminder).mkString(" "))
	}

	def main(args: Array[String]): Unit = {
		val cases = read(readInt)
		var nCase = 0
		for (nCase <- 1 to cases) {
			read(readInt)
			val arr = readArray[Long](readLong)
			solve(arr)
    }
  }
}


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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    val swap=(a:Array[Int], i:Int, j:Int)=>{
        val tmp=a(i)
        a(i)=a(j)
        a(j)=tmp
    }

    for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){
        swap(a,i,j)
        if(!isSorted(a)) {println((i+1)+" "+(j+1));exit(0)}
        swap(a,i,j)
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    if(a.max==a.min){
        println(-1)
        exit(0)
    }

    val swap=(a:Array[Int], i:Int, j:Int)=>{
        val tmp=a(i)
        a(i)=a(j)
        a(j)=tmp
    }

    for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){
        swap(a,i,j)
        if(!isSorted(a)) {println((i+1)+" "+(j+1));exit(0)}
        swap(a,i,j)
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase && arr(i)<arr(i-1)) return false
            if(!increase && arr(i)>arr(i-1)) return false
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    /*
    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }
    *
    */
    if(a.max==a.min){
        println(-1)
        exit(0)
    }

    val swap=(a:Array[Int], i:Int, j:Int)=>{
        val tmp=a(i)
        a(i)=a(j)
        a(j)=tmp
    }

    for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){
        swap(a,i,j)
        if(!isSorted(a)) {println((i+1)+" "+(j+1));exit(0)}
        swap(a,i,j)
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    for(i<-1 until n-1){
        if(i>max && a(i)<a(max) && a(i+1)<=a(max)) {println((max+1) +" " +(i+1)); exit(0)}
        if(i>min && a(i)>a(min) && a(i+1)>=a(min)) {println((min+1) + " "+(i+1)); exit(0)}
    }

    println(-1)
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    for(i<-1 until n-1){
        if(i!=max && a(i)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
        if(i!=min && a(i)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
    }

    println(-1)
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    for(i<-1 until n-1){
        if(i>max && a(i-1)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
        if(i>min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    if(isSorted(a)){
        println((max+1) +" " +(min+1)); exit(0)
    }
    else{
        for(i<-1 until n-1){
            if(i>max && a(i-1)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
            if(i>min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
        }
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    def maxsub(s:String):Int={
        val n=s.length
        val dp=new Array[Int](n)

        for(i<-1 until n){
            var j=i
            while(j>0 && s(i)!=s(dp(j-1))) j=dp(j-1)
            dp(i)=if(j>0) dp(j-1)+1 else 0
        }

        var j=dp(n-1)
        while(n%(n-j)!=0) j=dp(j-1)
        n/(n-j)
    }

    println(maxsub("a"))
    println(maxsub("a"*5))
    println(maxsub("ab"*1000))
    println(maxsub("byebye"))
    println(maxsub("codility"))
    println(maxsub("aabaaaba"))
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    for(i<-1 until n-1){
        if(i!=max && a(i-1)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
        if(i!=min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
    }

    println(-1)
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    if(isSorted(a) || max-min==1){
        println((max+1) +" " +(min+1)); exit(0)
    }
    else{
        for(i<-1 until n-1){
            if(i>max && a(i-1)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
            if(i>min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
        }
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){
        val tmp=a(i)
        a(i)=a(j)
        a(j)=tmp

        if(!isSorted(a)) {println((i+1)+" "+(j+1));exit(0)}
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, n1, n2) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt).sorted.reverse.take(n1 + n2)
  val min = Math.min(n1, n2)
  val max = Math.max(n1, n2)
  println(a.take(min).foldLeft(0l)(_+_).toDouble / min + a.drop(min).foldLeft(0l)(_+_).toDouble / max)
}

import java.io._
import scala.io.Source

import scala.annotation.tailrec

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line = lines.next()
    val parms = line.split(" ").map(_.toInt)
    val n = parms(0)
    val n1 = parms(1)
    val n2 = parms(2)
    val as = lines.next().split(" ").map(_.toLong)
    val soln = solve(n, n1, n2, as)
    bw.write(soln.toString)
    bw.newLine()
  }

  def solve(n: Int, n1: Int, n2: Int, as: Array[Long]): Double = {
    val nMin = math.min(n1, n2)
    val nMax = math.max(n1, n2)
    val asorted = as.map(- _).sorted
    val (aMin, aRest) = asorted.splitAt(nMin)
    val aMax = aRest.take(nMax)
    val mean1 = - aMin.sum / nMin.toDouble
    val mean2 = - aMax.sum / nMax.toDouble
    val sumOfMeans = mean1 + mean2
    sumOfMeans
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, n1, n2) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt).sorted.reverse.take(n1 + n2)
  val min = Math.min(n1, n2)
  val max = Math.max(n1, n2)
  println(a.take(min).sum.toDouble / min + a.drop(min).sum.toDouble / max)

}


object C extends App {

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

  val Array(n, q) = readInts(2)
  val as = readInts(n)

  val BITS = 20
  @inline def bit(i: Int) = 1 << i

  val minReachableWith = Array.fill(BITS){ n + 1 }
  for (b <- 0 until BITS) {
    if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1
  }

  val minReachable = Array.fill(n, BITS){ n + 1 }

  for (i <- n - 2 to 0 by -1) {
    val a = as(i)
    var b = 0
    while (b < BITS) {
      if ((a & bit(b)) > 0) {
        if (minReachableWith(b) < n) {
          val j = minReachableWith(b)
          var b2 = 0
          while (b2 < BITS) {
            if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)
            b2 += 1
          }
        }
        minReachableWith(b) = i
        minReachable(i)(b) = i
      }
      b += 1
    }
    var b2 = 0
    while (b2 < BITS) {
      if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2)
      b2 += 1
    }
  }

  val reachable = Array.fill(q)(false)
  for (i <- 0 until q) {
    val Array(l0, r0) = readInts(2)
    val l = l0 - 1
    val r = r0 - 1
    var b = 0
    while (b < BITS) {
      if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true
      b += 1
    }
  }

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

  println(reachable.map(if (_) "Shi" else "Fou").mkString("\n"))

  Console.flush
}

object C extends App {

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

  val Array(n, q) = readInts(2)
  val as = readInts(n)

  val BITS = 20
  def bit(i: Int) = 1 << i

  val minReachableWith = Array.fill(BITS){ n + 1 }
  for (b <- 0 until BITS) {
    if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1
  }

  val minReachable = Array.fill(n, BITS){ n + 1 }

  for (i <- n - 2 to 0 by -1) {
    val a = as(i)
    for (b <- 0 until BITS) {
      if ((a & bit(b)) > 0) {
        if (minReachableWith(b) < n) {
          val j = minReachableWith(b)
          for (b2 <- 0 until BITS) {
            if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)
          }
        }
        minReachableWith(b) = i
        minReachable(i)(b) = i
      }
    }
    for (b2 <- 0 until BITS) {
      if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2)
    }
  }

  val reachable = Array.fill(q)(false)
  for (i <- 0 until q) {
    val Array(l0, r0) = readInts(2)
    val l = l0 - 1
    val r = r0 - 1
    for (b <- 0 until BITS) {
      if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true
    }
  }

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

  println(reachable.map(if (_) "Shi" else "Fou").mkString("\n"))

  Console.flush
}

object C extends App {

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

  val Array(n, q) = readInts(2)
  val as = readInts(n)

  val BITS = 20
  @inline def bit(i: Int) = 1 << i

  val minReachableWith = Array.fill(BITS){ n + 1 }
  for (b <- 0 until BITS) {
    if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1
  }

  val minReachable = Array.fill(n, BITS){ n + 1 }

  for (i <- n - 2 to 0 by -1) {
    val a = as(i)
    var b = 0
    while (b < BITS) {
      if ((a & bit(b)) > 0) {
        if (minReachableWith(b) < n) {
          val j = minReachableWith(b)
          var b2 = 0
          while (b2 < BITS) {
            if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)
            b2 += 1
          }
        }
        minReachableWith(b) = i
        minReachable(i)(b) = i
      }
      b += 1
    }

  }

  val reachable = Array.fill(q)(false)
  for (i <- 0 until q) {
    val Array(l0, r0) = readInts(2)
    val l = l0 - 1
    val r = r0 - 1
    var b = 0
    while (b < BITS) {
      if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true
      b += 1
    }
  }

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

  println(reachable.map(if (_) "Shi" else "Fou").mkString("\n"))

  Console.flush
}

object C extends App {

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

  val Array(n, q) = readInts(2)
  val as = readInts(n)

  val BITS = 20
  def bit(i: Int) = 1 << i

  val minReachableWith = Array.fill(BITS){ n + 1 }
  for (b <- 0 until BITS) {
    if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1
  }

  val minReachable = Array.fill(n, BITS){ n + 1 }

  for (i <- n - 2 to 0 by -1) {
    val a = as(i)
    for (b <- 0 until BITS) {
      if ((a & bit(b)) > 0) {
        if (minReachableWith(b) < n) {
          val j = minReachableWith(b)
          for (b2 <- 0 until BITS) {
            if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2) : @inline
          }
        }
        minReachableWith(b) = i
        minReachable(i)(b) = i
      } : @inline
    }
    for (b2 <- 0 until BITS) {
      if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2) : @inline
    }
  }

  val reachable = Array.fill(q)(false)
  for (i <- 0 until q) {
    val Array(l0, r0) = readInts(2)
    val l = l0 - 1
    val r = r0 - 1
    for (b <- 0 until BITS) {
      if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true : @inline
    }
  }

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

  println(reachable.map(if (_) "Shi" else "Fou").mkString("\n"))

  Console.flush
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val team1 = in.next()
  val team2 = in.next()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().split(" "))
  var t1_1 = Set.empty[Int]
  var t1_2 = Map.empty[Int, Int]
  var t2_1 = Set.empty[Int]
  var t2_2 = Map.empty[Int, Int]
  data.foreach {
    case Array(time, "h", number, color) if t1_2.contains(number.toInt) =>
    case Array(time, "h", number, "r") => t1_2 += (number.toInt -> time.toInt)
    case Array(time, "h", number, "y") if t1_1.contains(number.toInt) => t1_2 += (number.toInt -> time.toInt)
    case Array(time, "h", number, "y") => t1_1 += number.toInt
    case Array(time, "a", number, color) if t2_2.contains(number.toInt) =>
    case Array(time, "a", number, "r") => t2_2 += (number.toInt -> time.toInt)
    case Array(time, "a", number, "y") if t2_1.contains(number.toInt) => t2_2 += (number.toInt -> time.toInt)
    case Array(time, "a", number, "y") => t2_1 += number.toInt
  }
  println((t1_2.map {
    case(number, time) => (time, team1, number)
  }.toList ::: t2_2.map {
    case(number, time) => (time, team2, number)
  }.toList).sorted.map(t => s"${t._2} ${t._3} ${t._1}").mkString("\n"))

}

import java.util.StringTokenizer
import scala.collection.mutable.Map

object _493A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val home = next
  val away = next
  val homeYellow = Map[Int, Int]()
  val awayYellow = Map[Int, Int]()
  val homeRed = Map[Int, Int]()
  val awayRed = Map[Int, Int]()

  val a = (1 to next.toInt).map(i => (1 to 4).map(j => next)).toArray.sortBy(arr => arr(0).toInt)
  for (event <- a) {
    val t = event(0).toInt
    val yellow = if (event(1) == "h") homeYellow else awayYellow
    val red = if(event(1) == "h") homeRed else awayRed
    val player = event(2).toInt
    if (event(3) == "y") {
      if (yellow.contains(player)) {
        if (red.contains(player)) red(player) = red(player) min t else red += ((player, t))
      }
      else yellow += ((player, t))
    } else {
      if (red.contains(player)) red(player) = red(player) min t
      else red += ((player, t))
    }
  }

  val cb = homeRed.toArray.map(i => (home, i._1, i._2))
  val wb = awayRed.toArray.map(i => (away, i._1, i._2))
  (cb ++ wb).sortBy(i => i._3).foreach(i => println("%s %d %d".format(i._1, i._2, i._3)))
}

object Main {
    def main(args: Array[String]) {
        val homename = io.StdIn.readLine()
        val guestname = io.StdIn.readLine()
        val fault_cnt = io.StdIn.readInt()
        val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>
            io.StdIn.readLine().split(" ")
        }.toArray
        val guest: Array[Int] = Array.fill[Int](100)(0)
        val home: Array[Int] = Array.fill[Int](100)(0)
        recs.foreach{ r =>
            val curteam = if(r(1) == "a") guest else home
            val curname = if(r(1) == "a") guestname else homename
            if(curteam(r(2).toInt) < 2) {
                if(r(3) == "y") curteam(r(2).toInt) += 1
                else curteam(r(2).toInt) += 2
                if(curteam(r(2).toInt) >= 2) {
                    println(curname + " " + r(2).toInt + " " + r(0).toInt)
                }
            }
        }
    }
}

import scala.collection.immutable.IndexedSeq

object ProblemARunner extends App {
  ProblemA.run()
}
object ProblemA {
  import scala.io.StdIn._

  private def relevantFouls(fouls: IndexedSeq[Foul]) = {
    val byPlayer = fouls.groupBy(foul => (foul.team, foul.player))
    byPlayer.values.toSeq.collect { case foulsByPlayer if foulsByPlayer.map(_.cards).sum >= 2 =>
        if(foulsByPlayer(0).cards == 2)
          foulsByPlayer(0)
        else
          foulsByPlayer(1)
    }.sortBy(_.time)
  }

  def run(): Unit = {
    val oneTeam = readTeamName()
    val otherTeam = readTeamName()
    val fouls = 1 to readFouls() map { _ =>
      Foul.read(oneTeam, otherTeam)
    }
    val relevant = relevantFouls(fouls)
    printFouls(relevant)
  }

  private def printFouls(fouls: Seq[Foul]) = {
    fouls.foreach(_.toOutput())
  }
  private def readTeamName(): String = {
    readLine()
  }
  private def readFouls(): Int = {
    readInt()
  }
  private case class Foul(time: Int, team: String, player: Int, cards: Int) {
    def toOutput() = {
      println(s"$team $player $time")
    }
  }
  private object Foul {
    def read(oneName: String, otherName: String): Foul = {
      val line = readLine().split(' ')
      val time = line(0).toInt
      val team = line(1) match {
        case "h" => oneName
        case "a" => otherName
      }
      val player = line(2).toInt
      val cards = line(3) match {
        case "y" => 1
        case "r" => 2
      }
      Foul(time, team, player, cards)
    }
  }

}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

import scala.annotation.tailrec

object A_VasyaAndFootbal {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val homeTeam = scanner.next()
    val awayTeam = scanner.next()

    val n = scanner.nextInt()

    val input = for (i <- 1 to n) yield {
      val time = scanner.nextInt()
      val teamId = scanner.next()
      val playerId = scanner.nextInt()
      val cardType = scanner.next()

      val teamName = teamId match {
        case "a" => awayTeam
        case "h" => homeTeam
      }

      (time, teamName, playerId, cardType)
    }

    //result (team, playerId, time, cardsCount)
    @tailrec def process (l : List[(Int, String, Int, String)], acc : Map[String, (String, Int, Int, Int)] = Map.empty) : Map[String, (String, Int, Int, Int)] = {
      l match {
        case x :: tail => {
          val playerId = x._2 + "_" + x._3
          val cardPoints = x._4 match {
            case "y" => 1
            case "r" => 2
            case _ => 0
          }

          val cardsCount = if (acc.contains(playerId)) acc(playerId)._4 else 0

          if (cardsCount >= 2) {
            process(tail, acc)
          } else {
            process(tail, acc + (playerId -> (x._2, x._3, x._1, cardsCount + cardPoints)))
          }
        }
        case Nil => acc
      }
    }

    val result = process(input.toList).filter(x => x._2._4 >= 2).toList.map(_._2).sortBy(x => x._3)

    for (x <- result) {
      out.println(s"${x._1} ${x._2} ${x._3}")
    }
  }
}

object Main extends App {

  val teamH = readLine
  val teamA = readLine

  def rename(team: String) = if(team == "h") teamH else teamA

  val games = readLine.toInt
  (1 to games).foldLeft(Map[(String, String), String]()) {
    case (acc, _) =>
      val Array(time, team, num, card) = readLine.split(" ")
      acc.get((team, num)) match {
        case None =>
          if(card == "r") println("%s %s %s".format(rename(team), num, time)) else ()
          acc + ((team, num) -> card)
        case Some("r") =>
          acc
        case Some("y") =>
          println("%s %s %s".format(rename(team), num, time))
          acc + ((team, num) -> "r")
      }
  }

}

import java.util.StringTokenizer
import scala.collection.mutable.Map

object _493A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val home = next
  val away = next
  val homeYellow = Map[Int, Int]()
  val awayYellow = Map[Int, Int]()
  val homeRed = Map[Int, Int]()
  val awayRed = Map[Int, Int]()

  val a = (1 to next.toInt).map(i => (1 to 4).map(j => next)).toArray.sortBy(arr => arr(0).toInt)
  for (event <- a) {
    val t = event(0).toInt
    val yellow = if (event(1) == "h") homeYellow else awayYellow
    val red = if(event(1) == "h") homeRed else awayRed
    val player = event(2).toInt
    if (event(3) == "y") {
      if (yellow.contains(player)) {
        yellow(player) = yellow(player) max t
        if (red.contains(player)) red(player) = red(player) min t else red += ((player, yellow(player)))
      }
      else yellow += ((player, t))
    } else {
      if (red.contains(player)) red(player) = red(player) min t
      else red += ((player, t))
    }
  }

  homeRed.toArray.sortBy(pair => pair._1).foreach(pair => println("%s %d %d".format(home, pair._1, pair._2)))
  awayRed.toArray.sortBy(pair => pair._1).foreach(pair => println("%s %d %d".format(away, pair._1, pair._2)))
}

object Main {
    def main(args: Array[String]) {
        val homename = io.StdIn.readLine()
        val guestname = io.StdIn.readLine()
        val fault_cnt = io.StdIn.readInt()
        val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>
            io.StdIn.readLine().split(" ")
        }.toArray
        val guest: Array[Int] = Array.fill[Int](99)(0)
        val home: Array[Int] = Array.fill[Int](99)(0)
        recs.foreach{ r =>
            val curteam = if(r(1) == "a") guest else home
            val curname = if(r(1) == "a") guestname else homename
            if(r(3) == "y") curteam(r(2).toInt) += 1
            if(r(3) == "r" || curteam(r(2).toInt) == 2) {
                println(curname + " " + r(2).toInt + " " + r(0).toInt)
            }
        }
    }
}

object Main {
    def main(args: Array[String]) {
        val homename = io.StdIn.readLine()
        val guestname = io.StdIn.readLine()
        val fault_cnt = io.StdIn.readInt()
        val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>
            io.StdIn.readLine().split(" ")
        }.toArray
        val guest: Array[Int] = Array.fill[Int](100)(0)
        val home: Array[Int] = Array.fill[Int](100)(0)
        recs.foreach{ r =>
            val curteam = if(r(1) == "a") guest else home
            val curname = if(r(1) == "a") guestname else homename
            if(r(3) == "y") curteam(r(2).toInt) += 1
            else curteam(r(2).toInt) += 2
            if(r(3) == "r" || curteam(r(2).toInt) == 2) {
                println(curname + " " + r(2).toInt + " " + r(0).toInt)
            }
        }
    }
}

object Main {
    def main(args: Array[String]) {
        val homename = io.StdIn.readLine()
        val guestname = io.StdIn.readLine()
        val fault_cnt = io.StdIn.readInt()
        val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>
            io.StdIn.readLine().split(" ")
        }.toArray
        val guest: Array[Int] = Array.fill[Int](100)(0)
        val home: Array[Int] = Array.fill[Int](100)(0)
        recs.foreach{ r =>
            val curteam = if(r(1) == "a") guest else home
            val curname = if(r(1) == "a") guestname else homename
            if(r(3) == "y") curteam(r(2).toInt) += 1
            if(r(3) == "r" || curteam(r(2).toInt) == 2) {
                println(curname + " " + r(2).toInt + " " + r(0).toInt)
            }
        }
    }
}

import scala.collection.immutable.IndexedSeq

object ProblemARunner extends App {
  ProblemA.run()
}
object ProblemA {
  import scala.io.StdIn._

  private def relevantFouls(fouls: IndexedSeq[Foul]) = {
    val byPlayer = fouls.groupBy(foul => (foul.team, foul.player))
    byPlayer.values.toSeq.collect { case foulsByPlayer if foulsByPlayer.map(_.cards).sum >= 2 =>
        foulsByPlayer.maxBy(_.time)
    }.sortBy(_.time)
  }

  def run(): Unit = {
    val oneTeam = readTeamName()
    val otherTeam = readTeamName()
    val fouls = 1 to readFouls() map { _ =>
      Foul.read(oneTeam, otherTeam)
    }
    val relevant = relevantFouls(fouls)
    printFouls(relevant)
  }

  private def printFouls(fouls: Seq[Foul]) = {
    fouls.foreach(_.toOutput())
  }
  private def readTeamName(): String = {
    readLine()
  }
  private def readFouls(): Int = {
    readInt()
  }
  private case class Foul(time: Int, team: String, player: Int, cards: Int) {
    def toOutput() = {
      println(s"$team $player $time")
    }
  }
  private object Foul {
    def read(oneName: String, otherName: String): Foul = {
      val line = readLine().split(' ')
      val time = line(0).toInt
      val team = line(1) match {
        case "h" => oneName
        case "a" => otherName
      }
      val player = line(2).toInt
      val cards = line(3) match {
        case "y" => 1
        case "r" => 2
      }
      Foul(time, team, player, cards)
    }
  }

}


import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn
import scala.reflect.ClassTag

object Main {
  final val MOD = 1000000007
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val ct = new mutable.HashMap[Long, Long]().withDefault(k => 0)
    for (v <- StdIn.readLine().split(" ").map(_.toInt)) {
      ct(v) += 1
    }
    val ctl = ct.toArray
    val prod = new SegTree(n)(new ModMul(MOD - 1))
    for (((k, v), i) <- ctl.zipWithIndex) {
      prod(i) = v + 1
    }
    var ans = 1L
    for (((k, v), i) <- ctl.zipWithIndex) {
      prod(i) = 1
      val s = (v * (v + 1) / 2) % (MOD - 1)
      val p = prod.query(0, n) * s % (MOD - 1)
      ans *= modPow(k, p, MOD)
      ans %= MOD
      prod(i) = v + 1
    }
    println(ans)
  }
  def modPow(x: Long, y: Long, mod: Int): Long = {
    @tailrec
    def rec(x: Long, y: Long, r: Long): Long = {
      if (y == 0) r
      else rec(x * x % mod, y / 2, if (y % 2 == 1) r * x % mod else r)
    }
    return rec(x, y, 1)
  }
}
trait Monoid[T] {
  def zero: T
  def mul(a: T, b: T): T
}

class SegTree[T: ClassTag](n0: Int)(m: Monoid[T]) {

  val n = {
    var n1 = 1
    while (n1 < n0) n1 <<= 1
    n1
  }

  val t: Array[T] = Array.fill[T](2 * n - 1)(m.zero)

  def set(a: Array[T]): Unit = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (r - l == 1) {
        if (l < a.length) t(k) = a(l)
        else t(k) = m.zero
        return t(k)
      } else {
        t(k) = m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
        return t(k)
      }
    }
    rec(0, 0, n)
  }

  def update(k0: Int, v: T): Unit = {
    var k = k0 + (n - 1)
    t(k) = v
    while (k > 0) {
      k = (k - 1) / 2
      t(k) = m.mul(t(2 * k + 1), t(2 * k + 2))
    }
  }

  def get(k0: Int): T = {
    return t(k0 + (n - 1))
  }

  def query(a: Int, b: Int): T = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (b <= l || r <= a) {
        return m.zero
      } else if (a <= l && r <= b) {
        return t(k)
      } else {
        return m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
      }
    }
    return rec(0, 0, n)
  }
}

class ModMul(mod: Int) extends Monoid[Long] {
  def zero = 1L
  def mul(a: Long, b: Long) = a * b % mod
}

object D extends App {

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

  val Array(m) = readInts(1)
  val ps = readInts(m)
  val psDist = ps.distinct
  val MOD = 1000000007L

  val cnts = Array.fill(ps.max.toInt + 1){ 0 }

  for (p <- ps) {
    val pi = p.toInt
    cnts(pi) += 1
  }

  val muls = Array.fill(ps.max.toInt + 1){ 0L }
  for (i <- cnts.indices) {
    if (cnts(i) > 0) {
      muls(i) = (cnts(i) + 1L) * cnts(i) / 2
    }
  }

  val powsLeft, powsRight = Array.fill(psDist.size){ 0L }
  var powL, powR = 1L

  for (i <- psDist.indices) {
    powsLeft(i) = powL
    powL = powL * (cnts(psDist(i).toInt) + 1) % (MOD - 1)
  }

  for (i <- psDist.indices.reverse) {
    powsRight(i) = powR
    powR = powR * (cnts(psDist(i).toInt) + 1) % (MOD - 1)
  }

  var res = BigInt(1)
  for (i <- psDist.indices) {
    val p = psDist(i)
    res = res * BigInt(p).modPow(BigInt(muls(p)) * powsLeft(i) * powsRight(i), MOD) % MOD
  }

  println(res)
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn
import scala.reflect.ClassTag

object Main {
  final val MOD = 1000000007
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val ct = new mutable.HashMap[Long, Long]().withDefault(k => 0)
    for (v <- StdIn.readLine().split(" ").map(_.toInt)) {
      ct(v) += 1
    }
    val ctl = ct.toArray
    val prod = new SegTree(n)(new ModMul(MOD - 1))
    for (((k, v), i) <- ctl.zipWithIndex) {
      prod(i) = v + 1
    }
    var ans = 1L
    for (((k, v), i) <- ctl.zipWithIndex) {
      prod(i) = 1
      val s = (v * (v + 1) / 2) % (MOD - 1)
      val p = prod.query(0, n) * s % (MOD - 1)
      ans *= modPow(k, p, MOD)
      ans %= MOD
      prod(i) = v + 1
    }
    println(ans)
  }
  def modPow(x: Long, y: Long, mod: Int): Long = {
    @tailrec
    def rec(x: Long, y: Long, r: Long): Long = {
      if (y == 0) r
      else rec(x * x, y / 2, if (y % 2 == 1) r * x % mod else r)
    }
    return rec(x, y, 1)
  }
}
trait Monoid[T] {
  def zero: T
  def mul(a: T, b: T): T
}

class SegTree[T: ClassTag](n0: Int)(m: Monoid[T]) {

  val n = {
    var n1 = 1
    while (n1 < n0) n1 <<= 1
    n1
  }

  val t: Array[T] = Array.fill[T](2 * n - 1)(m.zero)

  def set(a: Array[T]): Unit = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (r - l == 1) {
        if (l < a.length) t(k) = a(l)
        else t(k) = m.zero
        return t(k)
      } else {
        t(k) = m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
        return t(k)
      }
    }
    rec(0, 0, n)
  }

  def update(k0: Int, v: T): Unit = {
    var k = k0 + (n - 1)
    t(k) = v
    while (k > 0) {
      k = (k - 1) / 2
      t(k) = m.mul(t(2 * k + 1), t(2 * k + 2))
    }
  }

  def get(k0: Int): T = {
    return t(k0 + (n - 1))
  }

  def query(a: Int, b: Int): T = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (b <= l || r <= a) {
        return m.zero
      } else if (a <= l && r <= b) {
        return t(k)
      } else {
        return m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
      }
    }
    return rec(0, 0, n)
  }
}

class ModMul(mod: Int) extends Monoid[Long] {
  def zero = 1L
  def mul(a: Long, b: Long) = a * b % mod
}

import scala.collection._
import scala.util.Random

object D 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(m) = readInts(1)
  val ps = readBigs(m)
  //val ps = Array.fill(m){ BigInt(Random.nextInt(200000) + 2) }
  val MOD = 1000000007L

  var res = BigInt(1)
  for (p <- ps) {
    res = res * p.modPow(m, MOD) % MOD
  }

  println(res)
}

object D 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(m) = readInts(1)
  val ps = readBigs(m)
  val MOD = 1000000007L

  val cnts = Array.fill(ps.max.toInt + 1){ 0 }
  var pow = ps.size.toLong

  for (p <- ps) {
    val pi = p.toInt
    cnts(pi) += 1
  }

  val muls = Array.fill(ps.max.toInt + 1){ 0L }
  for (i <- cnts.indices) {
    if (cnts(i) > 0) {
      muls(i) = (cnts(i) + 1L) * cnts(i) / 2
    }
  }

  var res = BigInt(1)
  for (p <- ps.distinct) {
    val pi = p.toInt
    res = res * p.modPow(muls(pi) * (pow - cnts(pi) + 1), MOD) % MOD
  }

  println(res)
}

object D extends App {

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

  val Array(m) = readInts(1)
  val ps = readInts(m)
  val psDist = ps.distinct
  val MOD = 1000000007L

  val cnts = Array.fill(ps.max.toInt + 1){ 0 }

  for (p <- ps) {
    val pi = p.toInt
    cnts(pi) += 1
  }

  val muls = Array.fill(ps.max.toInt + 1){ 0L }
  for (i <- cnts.indices) {
    if (cnts(i) > 0) {
      muls(i) = (cnts(i) + 1L) * cnts(i) / 2
    }
  }

  val powsLeft, powsRight = Array.fill(psDist.size){ 0L }
  var powL, powR = 1L

  for (i <- psDist.indices) {
    powsLeft(i) = powL
    powL = powL * (cnts(ps(i).toInt) + 1) % (MOD - 1)
  }

  for (i <- psDist.indices.reverse) {
    powsRight(i) = powR
    powR = powR * (cnts(ps(i).toInt) + 1) % (MOD - 1)
  }

  var res = BigInt(1)
  for (i <- psDist.indices) {
    val p = ps(i)
    res = res * BigInt(p).modPow(BigInt(muls(p)) * powsLeft(i) * powsRight(i), MOD) % MOD
  }

  println(res)
}


import scala.collection.mutable

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF6B extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val m = nextInt
    val c = nextString.charAt(0)
    val matrix = Array.ofDim[Char](n, m)

    var minX = -1
    var minY = -1
    var maxX = -1
    var maxY = -1

    (0 until n).foreach { i =>
      val s = nextString
      (0 until m).foreach { j =>
        matrix(i)(j) = s.charAt(j)

        if (matrix(i)(j) == c) {
          if (minX == -1 && minY == -1) {
            minX = i
            minY = j
          }

          maxX = i
          maxY = j
        }
      }
    }

    val topLeft = (minX, minY)
    val bottomLeft = (maxX, minY)
    val topRight = (minX, maxY)
    val bottomRight = (maxX, maxY)

    var count = 0

    // top
    if (minX > 0) {
      val set = mutable.HashSet[Char]()
      (minY to maxY).foreach { j =>
        val color = matrix(minX - 1)(j)
        if (color != '.')
          set += color
      }
      count += set.size
    }

    // left
    if (minY > 0) {
      val set = mutable.HashSet[Char]()
      (minX to maxX).foreach { i =>
        val color = matrix(i)(minY - 1)
        if (color != '.')
          set += color
      }

      count += set.size
    }

    // bottom
    if (maxX < n - 1) {
      val set = mutable.HashSet[Char]()
      (minY to maxY).foreach { j =>
        val color = matrix(maxX + 1)(j)
        if (color != '.')
          set += color
      }

      count += set.size
    }

    // right
    if (maxY < m - 1) {
      val set = mutable.HashSet[Char]()
      (minX to maxX).foreach { i =>
        val color = matrix(i)(maxY + 1)
        if (color != '.')
          set += color
      }
      count += set.size
    }

    out.println(count)
  }

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

import java.util.Scanner

object BPresidentRoom extends App {

  val scanner = new Scanner(System.in)

  val rows = scanner.nextInt()
  val cols = scanner.nextInt()
  val col = scanner.next()(0)

  val room = Array.ofDim[Char](rows, cols)

  for (y <- 0 until rows) yield {
    room(y) = scanner.next().toCharArray
  }

  val c = for (y <- 0 until rows;
               x <- 0 until cols;
               p = (y, x) if room(y)(x) == col) yield neighbours(p._1, p._2)

  val res: List[(Int, Int)] = c.flatten.toList

  println(res.map(i => room(i._1)(i._2)).filter(p => p != '.' && p != col).distinct.size)

  def neighbours(x: Int, y: Int): List[(Int, Int)] = {
    def n(a: Int, b: Int): List[(Int, Int)] = if (a < 0 || b < 0 || a >= rows || b >= cols) Nil else List((a, b))
    n(x - 1, y) ++ n(x + 1, y) ++ n(x, y - 1) ++ n(x, y + 1)
  }

}

object B6 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m, c) = {
      val tl = tokenizeLine
      Array(tl.nextToken.toInt, tl.nextToken.toInt, tl.nextToken.head)
    }
    val set = cu.Set.empty[Int]
    val room = Array.fill(n)(read.toCharArray)
    val delta = Array((0,1), (-1,0), (1,0), (0,-1))
    for(i <- 0 until n; j <- 0 until m if room(i)(j) == c) {
      for((dx, dy) <- delta) {
        if(i+dx >= 0 && i+dx < n && j+dy >= 0 && j+dy < m && !Array('.', c).contains(room(i+dx)(j+dy)))
          set.add(room(i+dx)(j+dy))
      }
    }
    println(set.size)
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val m = nextInt
    val presidentColor = next.toCharArray()(0)
    val cabinet = new Array[Array[Char]](n + 2)
    for (i <- 0 until n + 2) {
      cabinet(i) = new Array[Char](m + 2)
      Arrays.fill(cabinet(i), '.')
    }
    for (i <- 1 to n) {
      val str = next.toCharArray
      for (j <- 1 to m) {
        cabinet(i)(j) = str(j - 1)
      }
    }
    var ans = 0
    val colors = new util.HashSet[Char]()
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    for (i <- 1 to n) {
      for (j <- 1 to m) {
        if (cabinet(i)(j) == presidentColor) {
          for (k <- 0 until 4) {
            val testedColor = cabinet(i + dx(k))(j + dy(k))
            if (testedColor != presidentColor && testedColor != '.' && !colors.contains(testedColor)) {
              ans += 1
              colors.add(testedColor)
            }
          }
        }
      }
    }
    out.println(ans)

  }

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

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var in = readLine.split(" ")
    var Array(n, m) = Array(in(0).toInt, in(1).toInt);
    var c = in(2).head;
    var arr = Array.ofDim[Char](n, m);
    for (i <- 0 until n) {
      arr(i) = readLine.toCharArray();
    }
    //doSomething(array, i, j)
    var set = Set[Char]();
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (arr(i)(j) == c) {
          if (j < m - 1 && arr(i)(j + 1) != '.' && arr(i)(j + 1) != c) {
            set.add(arr(i)(j + 1));
          }
          if (j > 0 && arr(i)(j - 1) != '.' && arr(i)(j - 1) != c) {
            set.add(arr(i)(j - 1));
          }
          if (i < n - 1 && arr(i + 1)(j) != '.' && arr(i + 1)(j) != c) {
            set.add(arr(i + 1)(j));
          }
          if (i > 0 && arr(i - 1)(j) != '.' && arr(i - 1)(j) != c) {
            set.add(arr(i - 1)(j));
          }
        }
      }
    }
    println(set.size);
  }

}

object main extends App with fastIO {

  val dx = Array(-1, 0, 1, 0)
  val dy = Array(0, -1, 0, 1)

  val Array(n :Int, m :Int, p :String) = readLine split(" ") map(s => if (s(0).isDigit) s.toInt else s)
  val a = Array.fill(n)(readLine)

  def ok(x :Int, y :Int) = x >= 0 && y >= 0 && x < n && y < m

  var set = Set[Char]()
  for (i <- 0 until n; j <- 0 until m if a(i)(j) == p(0))
  for (k <- 0 until 4 if ok(i + dx(k), j + dy(k)))
    set += a(i + dx(k))(j + dy(k))

  println(set count(c => c != '.' && c != p(0)))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def nextInt :Int = { in.nextToken; in.nval.toInt }
  def nextLong :Long ={ in.nextToken; in.nval.toLong }
  def nextDouble :Double = { in.nextToken; in.nval.toDouble }
  def readLine = bf.readLine

  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)

  def flush = out.flush
}

object P6B {
    def main(args : Array[String]) {
        val Array(nS, mS, cS) = readLine split ' '
        val (n, m, c) = (nS.toInt, mS.toInt, cS.head)
        val a = Array.fill(n){readLine}
        val d = for {
            x <- 0 until n
            y <- 0 until m
            if (a(x)(y) == c)
            (xA, yA) <- Array((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1))
            if (0 <= xA && xA < n)
            if (0 <= yA && yA < m)
            z = a(xA)(yA)
            if (z != '.' && z != c)
        } yield z
        println(d.distinct.size)
    }
}

import java.util._
object B {
  def main(args: Array[String]) = {
    val scanner = new Scanner(System.in)
    val n = scanner.nextInt
    val m = scanner.nextInt
    val color = scanner.nextLine.trim
    val input = for {
      i <- 0 until n
    } yield scanner.nextLine.trim.split("").toVector
    val desks = for {
      i <- 0 until n
      j <- 0 until m
      if input(i)(j) == color
      x <- (i-1).max(0) to (i+1).min(n-1)
      y <- (j-1).max(0) to (j+1).min(m-1)
      if (x - i).abs != (y - j).abs
    } yield input(x)(y)
    println(desks.toSet.filter(c => c != "." && c != color).size)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m, rs) = in.next().split(' ')
  val r = rs.head
  val data = (1 to n.toInt).map(_ => in.next().toCharArray)
  val lineSet = data.foldLeft(Set.empty[Char]) {
    case (set, line) => line.sliding(2).foldLeft(set) {
      case (nSet, Array(x, y)) if x == r || y == r => nSet + y + x
      case (nSet, _) => nSet
    }
  }
  val res = (0 until m.toInt).foldLeft(lineSet) {
    case (set, column) => data.map(_(column)).toArray.sliding(2).foldLeft(set) {
      case (nSet, Array(x, y)) if x == r || y == r => nSet + y + x
      case (nSet, _) => nSet
    }
  } - r - '.'
  println(res.size)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m, rs) = in.next().split(' ')
  val r = rs.head
  val data = (1 to n.toInt).map(_ => in.next().toCharArray)
  val lineSet = data.foldLeft(Set.empty[Char]) {
    case (set, line) => line.sliding(2).foldLeft(set) {
      case (nSet, Array(x, y)) if (x == r || y == r) && x != '.' && y != '.' => nSet + y + x
      case (nSet, _) => nSet
    }
  }
  val res = (0 until m.toInt).foldLeft(lineSet) {
    case (set, column) => data.map(_(column)).toArray.sliding(2).foldLeft(set) {
      case (nSet, Array(x, y)) if x == r || y == r && x != '.' && y != '.' => nSet + y + x
      case (nSet, _) => nSet
    }
  } - r
  println(res.size)
}

import java.util.Scanner

object BPresidentRoom extends App {

  val scanner = new Scanner(System.in)

  val rows = scanner.nextInt()
  val cols = scanner.nextInt()
  val col = scanner.next()(0)

  val room = Array.ofDim[Char](rows, cols)

  for (y <- 0 until rows) yield {
    room(y) = scanner.next().toCharArray
  }

  val c = for (y <- 0 until rows;
               x <- 0 until cols;
               p = (y, x) if room(y)(x) == col) yield neighbours(p._1, p._2)

  val res: List[(Int, Int)] = c.flatten.toList

  println(res.map(i => room(i._1)(i._2)).filter(p => p != '.' && p != col).distinct.size)

  def neighbours(x: Int, y: Int): List[(Int, Int)] = {
    def n(a: Int, b: Int): List[(Int, Int)] = if (a < 0 || b < 0 || a >= cols || b >= rows) Nil else List((a, b))
    n(x - 1, y) ++ n(x + 1, y) ++ n(x, y - 1) ++ n(x, y + 1)
  }

}

object main extends App with fastIO {

  val dx = Array(-1, 0, 1, 0)
  val dy = Array(0, -1, 0, 1)

  val Array(n :Int, m :Int, p :String) = readLine split(" ") map(s => if (s(0).isDigit) s.toInt else s)
  val a = Array.fill(n)(readLine)

  def ok(x :Int, y :Int) = x >= 0 && y >= 0 && x < n && y < m

  var set = Set[Char]()
  for (i <- 0 until n; j <- 0 until m if a(i)(j) == p(0))
  for (k <- 0 until 4 if ok(i + dx(k), j + dy(k)))
    set += a(i + dx(k))(j + dy(k))

  println(set.size)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def nextInt :Int = { in.nextToken; in.nval.toInt }
  def nextLong :Long ={ in.nextToken; in.nval.toLong }
  def nextDouble :Double = { in.nextToken; in.nval.toDouble }
  def readLine = bf.readLine

  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)

  def flush = out.flush
}


import scala.collection.mutable.ArrayBuffer

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m    = in.nextInt()
      val data = in.nextLineInt(m)

      var (largest1, largest2, largest3, largest4, largest5) =
        (Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue)
      var (smallest1, smallest2, smallest3, smallest4) = (Int.MaxValue, Int.MaxValue, Int.MaxValue, Int.MaxValue)

      data.foreach(d => {
        if (d <= smallest1) {
          smallest4 = smallest3
          smallest3 = smallest2
          smallest2 = smallest1
          smallest1 = d
        } else if (d <= smallest2) {
          smallest4 = smallest3
          smallest3 = smallest2
          smallest2 = d
        } else if (d <= smallest3) {
          smallest4 = smallest3
          smallest3 = d
        } else if (d <= smallest4) {
          smallest4 = d
        }
        if (d >= largest1) {
          largest5 = largest4
          largest4 = largest3
          largest3 = largest2
          largest2 = largest1
          largest1 = d
        } else if (d >= largest2) {
          largest5 = largest4
          largest4 = largest3
          largest3 = largest2
          largest2 = d
        } else if (d >= largest3) {
          largest5 = largest4
          largest4 = largest3
          largest3 = d
        } else if (d >= largest4) {
          largest5 = largest4
          largest4 = d
        } else if (d >= largest5) {
          largest5 = d
        }
      })
      val r1 = smallest1.toLong * smallest2 * smallest3 * smallest4 * largest1
      val r2 = smallest1.toLong * smallest2 * largest1 * largest2 * largest3
      val r3 = largest1.toLong * largest2 * largest3 * largest4 * largest5

      /*println((largest1, largest2, largest3, largest4, largest5))
      println((smallest1, smallest2, smallest3, smallest4))
      println(r1, r2, r3)*/

      val r = math.max(math.max(r1, r2), r3)
      println(r)
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

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

  val t = readInt()

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

    val ans = (0 until 5)
      .foldLeft(List.empty[Int])((is, i) => i :: (n - i - 1) :: is)
      .distinct
      .combinations(5)
      .foldLeft(Long.MinValue)(_ max _.foldLeft(1L)(_ * an(_)))

    println(ans)

  }
}

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

  val t = readInt()

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

    // format: off
    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList
    // format: on

    val ans = xs.indices.foldLeft(Long.MinValue) {
      case (ans, i) if ys.length >= 1 - i =>
        val x = xs.take(i + 1).product
        val y = ys.takeRight(1 - i).product
        val z = an(n + 2 * i - 3)
        ans max (x * y * z)
      case (ans, _) => ans
    }

    println(ans)
  }
}

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

  val t = readInt()

  // format: off
  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toLong).sorted

    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val zs =
      if (xs.length == 2 && ys.length == 1) xs
      else (xs ++ ys).sorted(Ordering.Long.reverse).take(2)

    val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product

    println(ans)
  }
}

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

  val t = readInt()

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

    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
  case Array(a, b) => a * b
    }.toList

    val zs = (xs ++ ys).sorted(Ordering.Long.reverse).take(2)

    val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product

    println(ans)
  }
}

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

  val t = readInt()

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

    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

val zs =
  if (ys.length == 1)
    xs.sorted(Ordering.Long.reverse)
  else
    (xs ++ ys).sorted(Ordering.Long.reverse).take(2)

    val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product

    println(ans)
  }
}

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

  val t = readInt()

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

    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
  case Array(a, b) => a * b
    }.toList

    val zs = (xs ++ ys).sorted(Ordering.Long.reverse).take(2)

    val ans = an(n - zs.diff(xs).length - 1) * zs.product

    println(ans)
  }
}

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

  val t = readInt()

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

    val ans = (0 until 4)
      .foldLeft(List.empty[Int])((is, i) => i :: (n - i - 1) :: is)
      .distinct
      .combinations(5)
      .map(_.foldLeft(1L)((p, i) => p * an(i)))
      .toList
      .sorted(Ordering.Long.reverse)
      .head

    println(ans)

  }
}

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

  val t = readInt()

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

    // format: off
    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList
    // format: on

    val ans = (0 to xs.length).foldLeft(Long.MinValue) {
      case (product, count) =>
        val x = xs.take(2 - (2 - count).min(ys.length)).product
        val y = ys.takeRight(2 - count).product
        val z = an(n - 2 * (2 - count).min(ys.length) - 1)
        product max (x * y * z)
    }

    println(ans)
  }
}

import scala.collection.mutable.ArrayBuffer

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m    = in.nextInt()
      val data = in.nextLineInt(m)

      var (largest1, largest2, largest3, largest4, largest5) =
        (Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue)
      var (smallest1, smallest2, smallest3, smallest4) = (Int.MaxValue, Int.MaxValue, Int.MaxValue, Int.MaxValue)

      data.foreach(d => {
        if (d <= smallest1) {
          smallest4 = smallest3
          smallest3 = smallest2
          smallest2 = smallest1
          smallest1 = d
        } else if (d <= smallest2) {
          smallest4 = smallest3
          smallest3 = smallest2
          smallest2 = d
        } else if (d <= smallest3) {
          smallest4 = smallest3
          smallest3 = d
        } else if (d <= smallest4) {
          smallest4 = d
        }
        if (d >= largest1) {
          largest5 = largest4
          largest4 = largest3
          largest3 = largest2
          largest2 = largest1
          largest1 = d
        } else if (d >= largest2) {
          largest5 = largest4
          largest4 = largest3
          largest3 = largest2
          largest2 = d
        } else if (d >= largest3) {
          largest5 = largest4
          largest4 = largest3
          largest3 = d
        } else if (d >= largest4) {
          largest5 = largest4
          largest4 = d
        } else if (d >= largest5) {
          largest5 = d
        }
      })

      val r1 = smallest1 * smallest2 * smallest3 * smallest4 * largest1
      val r2 = smallest1 * smallest2 * largest1 * largest2 * largest3
      val r3 = largest1 * largest2 * largest3 * largest4 * largest5

      /*      println((largest1, largest2, largest3, largest4, largest5))
      println((smallest1, smallest2, smallest3, smallest4))
      println(r1, r2, r3)*/

      val r = math.max(math.max(r1, r2), r3)
      println(r)
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}


import scala.collection.mutable

object D 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 ys = readInts(n)

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

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

  def can(limit: Long): Boolean = {
    var i = 0
    val isUsed = mutable.HashSet.empty[Int]
    var ok = true
    while (i < n) {
      var y = ys(i)
      //println(limit, y)
      while (y > 1 && (y > limit || isUsed(y))) {
        //y = if ((y & 1) == 0) y / 2 else (y - 1) / 2
        y >>= 1
      }
      if (isUsed(y)) {
        ok = false
        i = n
      } else {
        xs(i) = y
        isUsed += y
      }
      i += 1
    }
    ok
  }

  val max = binSearch(n, ys.max)
  can(max)

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

  println(xs.mkString(" "))

  Console.flush
}

object CF{
	import scala.io.StdIn.{readLine, readInt}
	import scala.collection.mutable.{Set, PriorityQueue}

	def main(args: Array[String]){
		val n:Int = readInt()
		val Y: List[Int] = readLine().split(" ").map(_.toInt).toList

		val s: Set[Int] = Set[Int](Y:_*)
		val pq: PriorityQueue[Int] = PriorityQueue[Int](Y:_*)

		val fpq = finalpq(pq, s)

		fpq.foreach(println(_))
	}

	def transform(s:Set[Int], y:Int): Int = y match{
		case 0 => 0
		case _ if s.contains(y) => transform(s, y/2)
		case _ => {
			s += y
			y
		}
	}

	def finalpq(pq:PriorityQueue[Int], s:Set[Int]): PriorityQueue[Int] = {
		val head = pq.head
		val at = transform(s, head)
		at match{
			case 0 => pq
			case _ => {
				pq.dequeue()
				pq += at
				finalpq(pq, s)
			}
		}
	}

}

object CF{
	import scala.io.StdIn.{readLine, readInt}
	import scala.collection.mutable.{Set, PriorityQueue}

	def main(args: Array[String]){
		val n:Int = readInt()
		val Y: List[Int] = readLine().split(" ").map(_.toInt).toList

		val s: Set[Int] = Set[Int](Y:_*)
		var pq: PriorityQueue[Int] = PriorityQueue[Int](Y:_*)

		var at = transform(s, pq.head)

		finalpq(pq, s)

		pq.foreach(println(_))
	}

	def transform(s:Set[Int], y:Int): Int = y match{
		case 0 => 0
		case _ if s.contains(y) => transform(s, y/2)
		case _ => {
			s += y
			y
		}
	}

	def finalpq(pq:PriorityQueue[Int], s:Set[Int]): PriorityQueue[Int] = {
		val head = pq.head
		val at = transform(s, head)
		at match{
			case 0 => pq
			case _ => {
				pq.dequeue()
				pq += at
				finalpq(pq, s)
			}
		}
	}

}


object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val Array(k, m) = in.next().split(" ").map(_.toInt)
  val a = in.next().split(" ").map(_.toInt).sorted.take(k).max
  val b = in.next().split(" ").map(_.toInt).sorted.reverse.take(m).min
  if (a < b) println("YES")
  else println("NO")
}

import java.util.Scanner
import Array._

object Codeforces extends App {
  val in = new Scanner(System.in)
  val na = in.nextInt()
  val nb = in.nextInt()
  val k = in.nextInt()
  val m = in.nextInt()
  var a = ofDim[Int](na)
  var b = ofDim[Int](nb)
  for (i <- 0 until na) {
    a(i) = in.nextInt()
  }
  for (i <- 0 until nb) {
    b(i) = in.nextInt()
  }
  if (a(k - 1) < b(nb - m)) {
    println("YES")
  } else {
    println("NO")
  }
}

object A572 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(na, nb) = readInts(2)
    val Array(k, m) = readInts(2)

    val a = readInts(na)
    val b = readInts(nb)

    if(a(k-1) < b(nb-m)) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _572A extends CodeForcesApp[String]({scanner => import scanner._
  val (na, nb, k, m) = (nextInt, nextInt, nextInt, nextInt)
  val (a, b) = (IndexedSeq.fill(na)(nextInt), IndexedSeq.fill(nb)(nextInt))
  val maxA = a(k-1)
  val remB = b.dropWhile(_ <= maxA)
  if (remB.size >= m) "YES" else "NO"
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object A extends App {
  val Array(na, nb) = readLine().split(" ").map(_.toInt)
  val Array(k, m) = readLine().split(" ").map(_.toInt)
  val A = readLine().split(" ").map(_.toInt)
  val B = readLine().split(" ").map(_.toInt)

  if (k > A.length || m > B.length || A.take(k).last >= B.takeRight(m).head) println("NO") else println("YES")
}

import scala.util.control.Breaks._

object GukiZ {
  def main(args: Array[String]) {
    val firstLine = scala.io.StdIn.readLine()
    val arraysLength = firstLine.split(" ") map (_.toInt)
    val aLength: Int = arraysLength(0)
    val bLength: Int = arraysLength(1)
    val secondLine = scala.io.StdIn.readLine()
    val limits = secondLine.split(" ") map (_.toInt)
    val k: Int = limits(0)
    val m: Int = limits(1)
    val thirdLine = scala.io.StdIn.readLine()
    val arrayA = thirdLine.split(" ") map (_.toInt)
    val fourthLine = scala.io.StdIn.readLine()
    val arrayB = fourthLine.split(" ") map (_.toInt)
    var mayor = false

    for (i <- 0 until k) {
      breakable{for(j <- (bLength-m) until bLength){
        if (arrayA(i) >= arrayB(j))
        mayor = true
        break
      }}

    }
    if (mayor)
      println("NO")
    else
      println("YES")

  }

}

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

object Vraag1 {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def main(args: Array[String]) {
     val _ = readInts()
     val km = readInts()
     val a = readInts
     val b = readInts
     val k = km(0)
     val m = km(1)
     if (a(k-1) < b.reverse(m-1)) println("YES") else println("NO")

   }

}

object A572 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(na, nb) = readInts(2)
    val Array(k, m) = readInts(2)

    val a = readInts(na)
    val b = readInts(nb)

    if(a(m-1) < b(nb-m)) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

import scala.io.StdIn._

object A extends App {
//  val Array(na, nb) = readLine().split(" ").map(_.toInt)
//  val Array(k, m) = readLine().split(" ").map(_.toInt)
//  val A = readLine().split(" ").map(_.toInt)
//  val B = readLine().split(" ").map(_.toInt)
  val k = 5
  val m = 2
  val A = Array(1, 1, 1, 1, 1)
  val B = Array(2, 2)

  if (k > A.length || m > B.length || A.take(k).last >= B.takeRight(m).head) println("NO") else println("YES")
}

object GukiZ {
  def main(args: Array[String]) {
    val firstLine = scala.io.StdIn.readLine()
    val arraysLength = firstLine.split(" ") map (_.toInt)
    val aLength: Int = arraysLength(0)
    val bLength: Int = arraysLength(1)
    val secondLine = scala.io.StdIn.readLine()
    val limits = secondLine.split(" ") map (_.toInt)
    val k: Int = limits(0)
    val m: Int = limits(1)
    val thirdLine = scala.io.StdIn.readLine()
    val arrayA = thirdLine.split(" ") map (_.toInt)
    val fourthLine = scala.io.StdIn.readLine()
    val arrayB = fourthLine.split(" ") map (_.toInt)
    var mayor = false

    for (i <- 0 until k) {
      for(j <- 0 until m){
        if (arrayA(i) >= arrayB(j))
        mayor = true
      }

    }
    if (mayor)
      println("NO")
    else
      println("YES")

  }

}

object GukiZ {
  def main(args:Array[String]){
    val firstLine = scala.io.StdIn.readLine()
    val arraysLength = firstLine.split(" ") map (_.toInt)
    val aLength:Int = arraysLength(0)
    val bLength:Int = arraysLength(1)
    val secondLine = scala.io.StdIn.readLine()
    val limits = secondLine.split(" ") map (_.toInt)
    val k:Int = limits(0)
    val m:Int = limits(1)
    val thirdLine = scala.io.StdIn.readLine()
    val arrayA = thirdLine.split(" ") map (_.toInt)
    val fourthLine = scala.io.StdIn.readLine()
    val arrayB = fourthLine.split(" ") map (_.toInt)

    if(arrayA(k-1) >= arrayB(0))
      println("NO")
    else println("YES")
  }

}

object GukiZ {
  def main(args: Array[String]) {
    val firstLine = scala.io.StdIn.readLine()
    val arraysLength = firstLine.split(" ") map (_.toInt)
    val aLength: Int = arraysLength(0)
    val bLength: Int = arraysLength(1)
    val secondLine = scala.io.StdIn.readLine()
    val limits = secondLine.split(" ") map (_.toInt)
    val k: Int = limits(0)
    val m: Int = limits(1)
    val thirdLine = scala.io.StdIn.readLine()
    val arrayA = thirdLine.split(" ") map (_.toInt)
    val fourthLine = scala.io.StdIn.readLine()
    val arrayB = fourthLine.split(" ") map (_.toInt)
    var mayor = false
    val startFor = aLength - (k)

    for (i <- 0 until k) {
      for(j <- 0 until m){
        if (arrayA(i) >= arrayB(j))
        mayor = true
      }

    }
    if (mayor)
      println("NO")
    else
      println("YES")

  }

}