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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val (a,b,c) = (ns(), ns(), ns())
        var oops = false
        REP(c.length) { i =>
          if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true
        }
        if(oops) out.println("NO")
        else out.println("YES")
      }
  }
}

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer

  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    (1 to n).foreach{ _ =>
      val astr = in.next
      val bstr = in.next
      val cstr = in.next
      val isOk = astr.zip(bstr).zip(cstr).forall{ case ((a,b),c) => ok(a,b,c)}
      out.println(if(isOk) "YES" else "NO")
    }
  }
  def ok(a: Char, b: Char, c: Char): Boolean = {
    b == c || a == c
  }

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

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = false

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val (a,b,c) = (ns(), ns(), ns())
        var oops = false
        REP(c.length) { i =>
          if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true
        }
        if(oops) out.println("NO")
        else out.println("YES")
      }
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = System.getenv("ONLINE_JUDGE") != null

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val (a,b,c) = (ns(), ns(), ns())
      if(a == b) {
        out.println("YES")
      } else {
        var oops = false
        REP(c.length) { i =>
          if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true
        }
        if(oops) out.println("NO")
        else out.println("YES")
      }
    }
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val (a,b,c) = (ns(), ns(), ns())
      if(a == b) {
        out.println("YES")
      } else {
        var oops = false
        REP(c.length) { i =>
          if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true
        }
        if(oops) out.println("NO")
        else out.println("YES")
      }
    }
  }
}


object A extends App {
  val t = scala.io.StdIn.readInt()

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

    val l = n * (a - b)
    val r = n * (a + b)

    if (r >= c - d && l <= c + d) println("YES")
    else println("NO")
  }
}

object App {
  def main(args: Array[String]): Unit = {
    val t = scala.io.StdIn.readInt()
    (for (i <- 1 to t) yield {
      val Array(n, a, b, c, d): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val grLeft = (a - b) * n
      val grRight = (a + b) * n
      grLeft <= (c + d) && grRight >= (c - d)
    }).map(x => {
      if (x) "YES"
      else "NO"
    }).foreach{
      println(_)
    }
  }
}


import scala.annotation.tailrec
import scala.io.StdIn

object Contest1313C2 {

  def floorsToTheLeft(m: Array[Long]): Vector[Long] = {
    val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {
      case (r, _) =>
        @tailrec
        def findNext(i: Int): Int = {
          val j = if (r.length > i) r(i) else i - 1
          if (j < 0 || m(j) < m(r.length)) j else findNext(j)
        }

        r :+ findNext(r.length)
    }
    closestLowerOnTheLeft.foldLeft(Vector.empty[Long]) {
      case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))
    }
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toLong
    val m = StdIn.readLine().trim.split("\\s+").map(_.toLong)
    val vLeft: Vector[Long] = floorsToTheLeft(m)
    val vRight = floorsToTheLeft(m.reverse).reverse
    val center = (vLeft, vRight, m).zipped.map(_ + _ - _).zipWithIndex.maxBy(_._1)._2
    val result = m.take(center).foldRight(Vector(m(center))) { case (mi, v) => math.min(mi, v.head) +: v } ++
      m.drop(center + 1).foldLeft(Vector(m(center))) { case (v, mi) => v :+ math.min(v.last, mi) }.drop(1)
    println(result.mkString(" "))
  }
}

import scala.annotation.tailrec
import scala.io.StdIn
import scala.math.min

object Contest1313C2 {

  def floorsToTheLeft(m: Array[Long]): Vector[Long] = {
    @tailrec
    def findNext(r: Vector[Int], i: Int): Int = if (i < 0 || m(i) < m(r.length)) i else findNext(r, r(i))

    val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {
      case (r, _) => r :+ findNext(r, r.length - 1)
    }
    closestLowerOnTheLeft.foldLeft(Vector.empty[Long]) {
      case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))
    }
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toLong
    val m = StdIn.readLine().trim.split("\\s+").map(_.toLong)
    val vLeft = floorsToTheLeft(m)
    val vRight = floorsToTheLeft(m.reverse).reverse
    val center = (vLeft, vRight, m).zipped.map( _ + _  - _).zipWithIndex.maxBy(_._1)._2
    val result = m.take(center).scanRight(m(center))(min) ++ m.drop(center + 1).scanLeft(m(center))(min).drop(1)
    println(result.mkString(" "))
  }
}

import scala.util.Random

case class SparseTable(blockSize: Int, blocks: Array[Int])

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val n = stdin.next().toInt
//  val n = 44905
  val data = stdin.next().split(' ').map(_.toLong)
//  val r = new Random(12)
//  val data = (0 until n).map(i =>  Math.abs(i).toLong).toArray
  var preparedArray = prepare(data)

  val heights = Array.ofDim[Long](n)

  val s1 = solve(data)
  println(heights.mkString(" "))

  def prepare(data: Array[Long]): SparseTable = {
    val blockSize = Math.sqrt(data.length).toInt
    SparseTable(blockSize, data.grouped(blockSize)
      .zipWithIndex.map(pair => pair._1.indices.minBy(i => pair._1(i)) + pair._2 * blockSize).toArray)
  }

  def solve(data: Array[Long])  {
    solve(data, 0, data.length - 1)
  }

  def solve(data: Array[Long], l: Int, r: Int)  {
    if (l > r) 0
    else if (l == r) {
      heights(l) = data(l)
      data(l)
    }
    else {
      val minIndex = calcMinIndex(preparedArray, data, l, r)
      val leftElements = minIndex - l
      val rightElements = r - minIndex
      if (leftElements > rightElements) { // we have moreElements on the left side, lets minimize right
        (minIndex to r).foreach(i => heights(i) = data(minIndex))
        solve(data, l, minIndex - 1)
      }
      else {
        (l to minIndex).foreach(i => heights(i) = data(minIndex))
        solve(data, minIndex + 1, r)
      }
    }
  }

  def calcMinIndex(sparseTable: SparseTable, data: Array[Long], l: Int, r: Int): Int = {
    val firstBlock = l / sparseTable.blockSize + (if (l % sparseTable.blockSize == 0) 0 else 1)
    val lastBlock = r / sparseTable.blockSize - (if (r % sparseTable.blockSize == (sparseTable.blockSize - 1)) 0 else 1)
    var minValue = Long.MaxValue
    var index = l
    if (firstBlock <= lastBlock) {
      val minIndex = sparseTable.blocks((firstBlock to lastBlock).minBy(blockIndex => data(sparseTable.blocks(blockIndex))))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    if (l <= Math.min(r, (firstBlock) * sparseTable.blockSize)) {
      val minIndex = (l to Math.min(r, (firstBlock) * sparseTable.blockSize)).minBy(i => data(i))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    if (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) <= r) {
      val minIndex = (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) to r).minBy(i => data(i))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    index
  }
}

import scala.util.Random

case class SparseTable(blockSize: Int, blocks: Array[Int])

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  //val n = stdin.next().toInt
  val n = 9
//  val data = stdin.next().split(' ').map(_.toLong).toList
  val r = new Random(2)
  val data = (0 until n).map(_ =>  Math.abs(r.nextInt()).toLong).toList
  var preparedArray = prepare(data)

  val heights = Array.ofDim[Long](n)

  val s1 = solve(data)
  println(heights.mkString(" "))

  def prepare(data: List[Long]): SparseTable = {
    val blockSize = Math.sqrt(data.length).toInt
    SparseTable(blockSize, data.grouped(blockSize)
      .zipWithIndex.map(pair => pair._1.indices.minBy(i => pair._1(i)) + pair._2 * blockSize).toArray)
  }

  def solve(data: List[Long]): Long = {
    solve(data, 0, data.length - 1)
  }

  def solve(data: List[Long], l: Int, r: Int): Long = {
    if (l > r) 0
    else if (l == r) {
      heights(l) = data(l)
      data(l)
    }
    else {
      val minIndex = calcMinIndex(preparedArray, data, l, r)
      val calculateLeft = solve(data, l, minIndex - 1)
      val calculateRight = solve(data, minIndex + 1, r)
      val leftSum = calculateLeft + (r - minIndex + 1) * data(minIndex)
      val rightSum = calculateRight + (minIndex - l + 1) * data(minIndex)
      if (leftSum > rightSum) {
        (minIndex to r).foreach(i => heights(i) = data(minIndex))
        leftSum
      } else {
        (l to minIndex).foreach(i => heights(i) = data(minIndex))
        rightSum
      }
    }
  }

  def calcMinIndex(sparseTable: SparseTable, data: List[Long], l: Int, r: Int): Int = {
    val firstBlock = l / sparseTable.blockSize + (if (l % sparseTable.blockSize == 0) 0 else 1)
    val lastBlock = r / sparseTable.blockSize - (if (r % sparseTable.blockSize == (sparseTable.blockSize - 1)) 0 else 1)
    var minValue = Long.MaxValue
    var index = l
    if (firstBlock <= lastBlock) {
      val minIndex = sparseTable.blocks((firstBlock to lastBlock).minBy(blockIndex => data(sparseTable.blocks(blockIndex))))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    if (l <= Math.min(r, (firstBlock) * sparseTable.blockSize)) {
      val minIndex = (l to Math.min(r, (firstBlock) * sparseTable.blockSize)).minBy(i => data(i))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    if (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) <= r) {
      val minIndex = (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) to r).minBy(i => data(i))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    index
  }
}

import scala.annotation.tailrec
import scala.io.StdIn

object Contest1313C2 {

  def floorsToTheLeft(m: Array[Int]): Vector[Int] = {
    val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {
      case (r, _) =>
        @tailrec
        def findNext(i: Int): Int = {
          val j = if (r.length > i) r(i) else i - 1
          if (j < 0 || m(j) < m(r.length)) j else findNext(j)
        }

        r :+ findNext(r.length)
    }
    closestLowerOnTheLeft.foldLeft(Vector.empty[Int]) {
      case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))
    }
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val m = StdIn.readLine().trim.split("\\s+").map(_.toInt)
    val vLeft: Vector[Int] = floorsToTheLeft(m)
    val vRight = floorsToTheLeft(m.reverse).reverse
    val center = (vLeft, vRight, m).zipped.map(_ + _ - _).zipWithIndex.maxBy(_._1)._2
    val result = m.take(center).foldRight(Vector(m(center))) { case (mi, v) => math.min(mi, v.head) +: v } ++
      m.drop(center + 1).foldLeft(Vector(m(center))) { case (v, mi) => v :+ math.min(v.last, mi) }.drop(1)
    println(result.mkString(" "))
  }
}


import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val n=readInt
    for(_<-1 to n){
        println(solve(readLine))
    }

    def solveone(str:String):String={
       val list=str.split(":")
       for(i<-0 until list.size)
           list(i)="0"*(4-list(i).size)+list(i)

       list.mkString(":")
    }

    def solve(str:String):String={
        val p=str.indexOfSlice("::");
        if(p>=0){
            val left=solveone(str.substring(0,p))
            val right=solveone(str.substring(p+2))
            val count=8-(left.size+right.size+2)/5
            left+":0000"*count+":"+right
        }
        else solveone(str)
    }
}

import java.util.Scanner
import scala.collection.mutable._
import java.net.InetAddress

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

  val n = sc.nextInt()

  for (_ <- 0 until n) {
    val ipv6 = InetAddress.getByName(sc.next).getHostAddress.split(":")
    println(ipv6.map(_.reverse.padTo(4, '0').reverse).mkString(":"))
  }
}

object Main extends App {

  import scala.io.{Source, StdIn}

  override def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    for (_ <- 1 to n) {
      val s = StdIn.readLine()
      var arr = s.split(":")
      if (s.startsWith("::")) arr = arr.drop(1)
      if (arr.length != 8 && !arr.contains("")) arr = arr ++ Seq("")
      val res = arr.map(
        part =>
          if (part.isEmpty) {
            "0000:" * (9 - arr.length)
          }
          else {
            ("0" * (4 - part.length) + part) + ":"
          }

      )
      println(res.mkString("").dropRight(1))
    }
  }
}

object Main extends App {

  import scala.io.{Source, StdIn}

  override def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    for (_ <- 1 to n) {
      val s = StdIn.readLine()
      var arr = s.split(":")
      if (arr.length != 8 && !arr.contains("")) arr = arr ++ Seq("")
      val res = arr.map(
        part =>
          if (part.isEmpty) {
            "0000:" * (9 - arr.length)
          }
          else {
            ("0" * (4 - part.length) + part) + ":"
          }
      )
      println(res.mkString("").dropRight(1))
    }
  }
}


object Solution extends App {

  def compare(str1: List[Char], str2: List[Char], change1: Option[Char], change2: Option[Char], changed: Boolean): Boolean =
    if (str1.isEmpty && str2.isEmpty)
      change1.isEmpty
    else if (str1.head == str2.head)
      compare(str1.tail, str2.tail, change1, change2, changed)
    else if (changed)
      false
    else if (change1.isEmpty)
      compare(str1.tail, str2.tail, Some(str1.head), Some(str2.head), changed)
    else if (change1.get == str2.head && change2.get == str1.head)
      compare(str1.tail, str2.tail, None, None, true)
    else false

  val in = scala.io.Source.stdin.getLines()
  val str1 = in.next()
  val str2 = in.next()
  if (str1.length == str2.length && compare(str1.toCharArray.toList,
    str2.toCharArray.toList, None, None, false)) println("YES")
  else println("NO")
}

object Main {
  def main(args: Array[String]) {
    val s1 = readLine()
    val s2 = readLine()
    if (s1.size != s2.size) println("NO")
    else {
      val zipped = s1.zip(s2).zipWithIndex
      val filtered = zipped.filter(t => t._1._1 != t._1._2)
      if (filtered.size != 2) println("NO")
      else {
        val t1 = filtered(0)
        val t2 = filtered(1)
        if (t1._1._1 == t2._1._2 && t2._1._1 == t1._1._2) println("YES")
        else println("NO")
      }
    }
  }
}

object A
{
  def main(args: Array[String])
  {
    val str1 = readLine.toCharArray
    val str2 = readLine.toCharArray

    if(str1.length != str2.length) println("NO")
    else
    {
      val n = str1.length
      if((0 until n).count(i => str1(i)!=str2(i)) != 2) println("NO")
      else
      {
        var firstFound = false
        var car1 = ' '
        var car2 = ' '
        for(i <- 0 until n)
        {
          if(str1(i)!=str2(i))
          {
            if(!firstFound)
            {
              car1 = str1(i)
              car2 = str2(i)
              firstFound = true
            }
            else
            {
              if(car1==str2(i) && car2==str1(i)) println("YES")
              else println("NO")
            }
          }
        }
      }
    }
  }
}

import com.sun.org.apache.xpath.internal.operations.Bool

/**
 * Created with IntelliJ IDEA.
 * User: Oleg
 * Date: 10.05.12
 * Time: 1:24
 * To change this template use File | Settings | File Templates.
 */

object A {
  val s1, s2 = readLine
  val (yes, no) = ("YES", "NO")

  def main(args: Array[String]) {
    println(good)
  }

  def good: String = {
    if (s1.length != s2.length) return no
    val inequality: (Int => Boolean) = (i => (s1(i) != s2(i)))
    val first = (0 until s1.length) find inequality
    val last = ((s1.length - 1) to 0 by -1) find inequality
    (first, last) match {
      case (Some(first), Some(last)) if first != last => {
        if (s1.substring(first + 1, last) != s2.substring(first + 1, last)) return no
        if (s1(first) != s2(last)) return no
        if (s1(last) != s2(first)) return no
        return yes
      }
      case _ => return no
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val s1 = readLine()
    val s2 = readLine()
    if (s1.size != s2.size) println("NO")
    else {
      val zipped = s1.zip(s2).zipWithIndex
      val filtered = zipped.filter(t => t._1._1 != t._1._2)
      if (filtered.size != 2) println("NO")
      else {
        val t1 = filtered(0)
        val t2 = filtered(1)
        if (t1._2 + 1 != t2._2) println("NO")
        else if (t1._1._1 == t2._1._2 && t2._1._1 == t1._1._2) println("YES")
        else println("NO")
      }
    }
  }
}


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

object B extends App {
  class Node {
    val conn = new mutable.HashSet[Int]
  }

  val n = readInt()
  val A = Array(Integer.MIN_VALUE) ++ readLine().split(" ").map(_.toInt)
  val G = Array.fill(n + 1)(new Node)

  for (i <- 1 to n) {
    val next = if (i < n) i + 1 else 1
    if (i < n) {
      G(i).conn += next
      G(next).conn += i
    }
    if (i != A(i)) {
      G(i).conn += A(i)
    }
//    println(i + " -> " + G(i).conn.mkString(","))
  }

  val visited = Array.fill(n + 1)(false)
  val cost = Array.fill(n + 1)(0)
  visited(1) = true

  val Q = new mutable.Queue[Int]
  Q.enqueue(1)

  while (Q.nonEmpty) {
    val curr = Q.dequeue()
    visited(curr) = true

    for (next <- G(curr).conn) {
      if (!visited(next)) {
        visited(next) = true
        cost(next) = cost(curr) + 1
        Q.enqueue(next)
      }
    }
  }

  println(cost.tail.mkString(" "))
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val dp = Array.fill(n+1)(Int.MaxValue)
    dp(0) = -1
    dp(1) = 0
    for(i <- 1 to n-1){
      val now = dp(i)
      dp(i+1) = Math.min(dp(i+1), now + 1)
      var sho = a(i)
      dp(sho) = Math.min(dp(sho), now + 1)
      var flag = true
      while(flag){
        // println(sho)
        if(dp(sho-1) > dp(sho) + 1){
          dp(sho-1) = dp(sho) + 1
          sho -= 1
        }
        else
          flag = false
      }
    }

    //
    print(dp(1))
    for(i <- 2 to n)
      print(" " + dp(i))
    println()
  }
}

object main
{
	def main ( args : Array[String] )
	{
		var n = Console.readLine().toInt;
		var str = Console.readLine();
		var to = new Array[Int](200010);
		var que = new Array[Int](200010);
		var dist = new Array[Int](200010);
		var now = 0;
		for ( a <- 0 to str.length()-1 )
		{
			if (str.charAt(a) == ' ') now = now + 1;
			else to(now) = to(now) * 10 + str.charAt(a) - '0';
		}

		for ( a <- 0 to n-1 )
		{
			dist(a) = -1;
			to(a) -= 1;
		}
		dist(0)=0;
		var front = 0;
		var tail = 0;
		while (front<=tail)
		{
			var now = que(front);
			front += 1;
			if (now > 0 && dist(now-1) == -1)
			{
				tail += 1;
				que(tail) = now-1;
				dist(now-1) = dist(now) + 1;
			}
			if (now < n-1 && dist(now+1) == -1)
			{
				tail += 1;
				que(tail) = now+1;
				dist(now+1) = dist(now) + 1;
			}
			if (dist(to(now)) == -1)
			{
				tail += 1;
				que(tail) = to(now);
				dist(to(now)) = dist(now) + 1;
			}
		}
		for ( a <- 0 to n-1)
		{
			print(dist(a));
			if (a==n-1) println();
			else print(" ");
		}
	}
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

/**
  * @author Baidin Dima
  */
object MikeAndShortcuts extends App {

  case class Edge(to: Int, w: Int)

  def readInput(): Array[ArrayBuffer[Edge]] = {
    val intersectionCount = scala.io.StdIn.readInt()

    val adjacencyList: Array[ArrayBuffer[Edge]] = new Array(intersectionCount)

    val shortcuts = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    adjacencyList.indices.foreach { case i ⇒
      val to = shortcuts(i)
      adjacencyList(i) = ArrayBuffer(Edge(to - 1, 1))
      if (i != intersectionCount - 1) {
        adjacencyList(i) += Edge(i + 1, 1)
      }
      if (i != 0) {
        adjacencyList(i) += Edge(i - 1, 1)
      }
    }
    adjacencyList
  }

  def dijkstra(adjacencyList: Array[ArrayBuffer[Edge]]): Unit = {
    val visited: Array[Boolean] = new Array(adjacencyList.length);
    visited(0) = true
    val distance: Array[Int] = new Array(adjacencyList.length);
    distance(0) = 0

    implicit val edgeOrdering: Ordering[Edge] = new Ordering[Edge] {
      override def compare(x: Edge, y: Edge): Int = y.w - x.w
    }

    val q: mutable.PriorityQueue[Edge] = new mutable.PriorityQueue[Edge]()

    adjacencyList(0).foreach { case edge ⇒ q += edge }

    while (q.nonEmpty) {
      val edge = q.dequeue()

      if (!visited(edge.to)) {
        visited(edge.to) = true
        distance(edge.to) = edge.w

        adjacencyList(edge.to).foreach(nEdge ⇒
          q += Edge(nEdge.to, edge.w + nEdge.w)
        )
      }
    }

    println(distance.mkString(" "))
  }

  dijkstra(readInput())

}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val dp = Array.fill(n+1)(Int.MaxValue)
    dp(1) = 0
    for(i <- 1 to n-1){
      val now = dp(i)
      dp(i+1) = Math.min(dp(i+1), now + 1)
      val sho = a(i)
      dp(sho) = Math.min(dp(sho), now + 1)
    }

    for(i <- (1 to n-1).reverse){
      if(dp(i) > dp(i+1) + 1)
        dp(i) = dp(i+1) + 1
    }

    //
    print(dp(1))
    for(i <- 2 to n)
      print(" " + dp(i))
    println()
  }
}

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

object B extends App {
  class Node {
    val conn = new mutable.ArrayBuffer[Int]
  }

  val n = readInt()
  val A = Array(Integer.MIN_VALUE) ++ readLine().split(" ").map(_.toInt)
  val G = Array.fill(n + 1)(new Node)

  for (i <- 1 to n) {
    val next = if (i < n) i + 1 else 1
    G(i).conn += next
    if (next != A(i) && A(i) != i) G(i).conn += A(i)
//    println(i + " -> " + G(i).conn.mkString(","))
  }

  val visited = Array.fill(n + 1)(false)
  val cost = Array.fill(n + 1)(0)
  visited(1) = true

  val Q = new mutable.Queue[Int]
  Q.enqueue(1)

  while (Q.nonEmpty) {
    val curr = Q.dequeue()
    visited(curr) = true

    for (next <- G(curr).conn) {
      if (!visited(next)) {
        visited(next) = true
        cost(next) = cost(curr) + 1
        Q.enqueue(next)
      }
    }
  }

  println(cost.tail.mkString(" "))
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

/**
  * @author Baidin Dima
  */
object MikeAndShortcuts extends App {

  case class Edge(to: Int, w: Int)

  def readInput(): Array[ArrayBuffer[Edge]] = {
    val intersectionCount = scala.io.StdIn.readInt()

    val adjacencyList: Array[ArrayBuffer[Edge]] = new Array(intersectionCount)

    val shortcuts = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    adjacencyList.indices.foreach { case i ⇒
      val to = shortcuts(i)
      adjacencyList(i) = ArrayBuffer(Edge(to - 1, 1))
      if (i != intersectionCount - 1) {
        adjacencyList(i) += Edge(i + 1, 1)
      }
    }
    adjacencyList
  }

  def dijkstra(adjacencyList: Array[ArrayBuffer[Edge]]): Unit = {
    val visited: Array[Boolean] = new Array(adjacencyList.length); visited(0) = true
    val distance: Array[Int] = new Array(adjacencyList.length); distance(0) = 0

    implicit val edgeOrdering: Ordering[Edge] = new Ordering[Edge] {
      override def compare(x: Edge, y: Edge): Int = x.w - y.w
    }

    val q: mutable.PriorityQueue[Edge]= new mutable.PriorityQueue[Edge]()

    adjacencyList(0).foreach{case edge ⇒ q += edge}

    while (q.nonEmpty) {
      val edge = q.dequeue()

      if (!visited(edge.to)) {
        visited(edge.to) = true
        distance(edge.to) = edge.w

        adjacencyList(edge.to).foreach(nEdge ⇒
          q += Edge(nEdge.to, edge.w + nEdge.w)
        )
      }
    }

    println(distance.mkString(" "))
  }

  dijkstra(readInput())

}


object C5 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    val d = Array.fill(str.length)(-1) // pos of corresponding open bracket
    val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular
    val stack = new java.util.Stack[Int]
    var i = 0
    while (i < str.length) {
      if (str(i) == '(') {
        stack.push(i)
      } else {
        if (stack.isEmpty) {
          d(i) = -1
          c(i) = -1
        } else {
          val top = stack.pop()
          d(i) = top
          c(i) = d(i)
          if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {
            c(i) = c(d(i) - 1)
          }
        }
      }
      i += 1
    }
    i = 0
    var max = 0
    var count = 0
    while (i < str.length) {
      if (c(i) != -1)
        if (max < i - c(i) + 1) {
          count = 1
          max = i - c(i) + 1
        } else if (max == i - c(i) + 1) {
          count += 1
        }
      i += 1
    }
    if (max == 0) {
      out.println("0 1")
    } else {
      out.println(s"${max} ${count}")
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object C5 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    val d = Array.fill(str.length)(-1) // pos of corresponding open bracket
    val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular
    val stack = new cu.Stack[Int]
    var i = 0
    while (i < str.length) {
      if (str(i) == '(') {
        stack.push(i)
      } else {
        if (stack.isEmpty) {
          d(i) = -1
          c(i) = -1
        } else {
          val top = stack.pop()
          d(i) = top
          c(i) = d(i)
          if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {
            c(i) = c(d(i) - 1)
          }
        }
      }
      i += 1
    }
    val maxs = c.zipWithIndex.map {
      case (value, idx) => if (value != -1) idx - value + 1 else 0
    }
    val max = maxs.max
    if (max == 0) {
      out.println("0 1")
    } else {
      out.println(s"${max} ${maxs.count(_ == max)}")
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object main extends App with fastIO {

  val s = " " + readLine
  val n = s.length - 1

  var a: Array[Int] = s.toArray.map( (c) => if (c == '(') 1 else -1 )

  a(0) = 0
  for (i <- 1 to n) a(i) += a(i - 1)
  a = a.map(_ + n)

  var first = Array.fill(2 * n + 1)(n + 1)
  var ans = for (i <- 1 to n) yield {
    s(i) match {
      case '(' => if (first(a(i - 1)) == n + 1) first(a(i - 1)) = i
      case ')' => first(a(i - 1)) = n + 1
    }
    i - first(a(i)) + 1
  }

  val answer = ans.max max 0
  print(answer + " " + ans.count(_ == answer))
  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
  }

  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()
}

object P5C {
    def main(args: Array[String]) {
        val s = readLine
        val n = s.size
        val a = Array.fill(n + n + 1){n}
        var d = n
        val answer = for (i <- 0 until n) yield {
            s(i) match {
                case '(' => {
                    if (a(d) == n) a(d) = i
                    d = d + 1
                }
                case ')' => {
                    a(d) = n
                    d = d - 1
                }
            }
            i - a(d) + 1
        }
        val m = answer.max max 0
        println(m + " " + answer.count{_ == m})
    }
}

object C {
  def main(args: Array[String]) = {
    lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)
    def insert(list: List[(Int, Int)], pair: (Int, Int)): List[(Int, Int)] = list match {
      case Nil => pair::Nil
      case head::tail =>
        if (head._1 > pair._1 && head._2 < pair._2) insert(tail, pair)
        else if (head._2 == pair._1 - 1) (head._1, pair._2)::tail
        else pair::list
    }
    def foldMethod(lists: (List[Int], List[(Int, Int)]), ch: (Char, Int)): (List[Int], List[(Int, Int)]) = lists match {
      case (opens, pairs) =>
        if(ch._1 == '(') (ch._2::opens, pairs)
        else if(opens.isEmpty) (opens, pairs)
        else (opens.tail, insert(pairs, (opens.head, ch._2)))
    }
    lazy val folded = input.foldLeft((List[Int](), List[(Int, Int)]()))(foldMethod)._2.map(p => p._2 - p._1 + 1)
    lazy val maxi   = if (folded.isEmpty) 0 else folded.max
    lazy val count  = if (folded.isEmpty) 1 else folded.count(_ == maxi)

    println(maxi + " " + count)
  }
}

import java.util
import java.util.Scanner

object CBalancedBraces extends App {

  val scanner = new Scanner(System.in)

  val input = scanner.next()
  val stack = new util.Stack[Int]

  var max = 0
  var maxNum = 0

  stack.push(-1)

  input.zipWithIndex foreach {
    item =>
      item._1 match {
        case '(' => stack.push(item._2)
        case ')' =>
          if (!stack.empty()) {
            stack.pop()
            if (!stack.empty()) {
              recordResult(item._2, stack.peek())
            }
          }
          if (stack.empty()) {
            stack.push(item._2)
          }

      }
  }

  if (max == 0) {
    println("0 1")
  } else {
    print(max + " ")
    println(maxNum)
  }

  def recordResult(start: Int, end: Int): Unit = {
    val item = start - end
    if (max < item) {
      max = item
      maxNum = 1
    } else if (max == item) maxNum += 1
  }

}

object C5 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    val d = Array.fill(str.length)(-1) // pos of corresponding open bracket
    val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular
    val stack = new cu.Stack[Int]
    var i = 0
    while (i < str.length) {
      if (str(i) == '(') {
        stack.push(i)
      } else {
        if (stack.isEmpty) {
          d(i) = -1
          c(i) = -1
        } else {
          val top = stack.pop()
          d(i) = top
          c(i) = d(i)
          if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {
            c(i) = c(d(i) - 1)
          }
        }
      }
      i += 1
    }
    i = 0
    var max = 0
    var count = 0
    while (i < str.length) {
      if (c(i) != -1)
        if (max < i - c(i) + 1) {
          count = 1
          max = i - c(i) + 1
        } else if (max == i - c(i) + 1) {
          count += 1
        }
      i += 1
    }
    if (max == 0) {
      out.println("0 1")
    } else {
      out.println(s"${max} ${count}")
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object main extends App with fastIO {

  val s = " " + readLine
  val n = s.length - 1

  var a: Array[Int] = s.toArray.map( (c) => if (c == '(') 1 else -1 )

  a(0) = 0
  for (i <- 1 to n) a(i) += a(i - 1)
  a = a.map(_ + n)

  var first = Array.fill(2 * n + 1)(n)
  var ans = for (i <- 1 to n) yield {
    s(i) match {
      case '(' => if (first(a(i - 1)) == n) first(a(i - 1)) = i
      case ')' => first(a(i - 1)) = n
    }
    i - first(a(i)) + 1
  }

  val answer = ans.max max 0
  print(answer + " " + ans.count(_ == answer))
  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
  }

  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()
}

object C {
  def main(args: Array[String]) = {
    lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)
    def insert(list: List[(Int, Int)], pair: (Int, Int)): List[(Int, Int)] = list match {
      case Nil => pair::Nil
      case head::tail =>
        if (head._1 > pair._1 && head._2 < pair._2) insert(tail, pair)
        else if (head._2 == pair._1 - 1) (head._1, pair._2)::tail
        else pair::list
    }
    def foldMethod(lists: (List[Int], List[(Int, Int)]), ch: (Char, Int)): (List[Int], List[(Int, Int)]) = lists match {
      case (opens, pairs) =>
        if(ch._1 == '(') (ch._2::opens, pairs)
        else if(opens.isEmpty) (opens, pairs)
        else (opens.tail, insert(pairs, (opens.head, ch._2)))
    }
    lazy val folded = input.foldLeft((List[Int](), List[(Int, Int)]()))(foldMethod)._2.map(p => {println(p); p._2 - p._1 + 1})
    lazy val maxi   = if (folded.isEmpty) 0 else folded.max
    lazy val count  = if (folded.isEmpty) 1 else folded.count(_ == maxi)

    println(maxi + " " + count)
  }
}

object C {
  def main(args: Array[String]) = {
    lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)
    def foldMethod(lists: (List[Int], List[Int]), ch: (Char, Int)): (List[Int], List[Int]) = lists match {
      case (opens, starts) =>
        if(ch._1 == '(') (ch._2::opens, -1::starts)
        else if(opens.isEmpty) (opens, -1::starts)
        else (opens.tail, opens.head::starts)
    }
    lazy val folded = input.foldLeft((List[Int](), List[Int]()))(foldMethod)._2.reverse
    def findStart(list: Vector[Int], index: Int): Vector[Int] = {
      if (index == -1) list :+ 0
      else if (index == 0) list :+ list.length
      else if (list(index - 1) != 0) list :+ (list.length - index + 1 + list(index - 1))
      else list :+ (list.length - index + 1)
    }
    lazy val result = folded.foldLeft(Vector.empty[Int])(findStart)
    lazy val maxi   = result.max
    lazy val count  = result.count(_ == maxi)

    if (maxi == 0) println("0 1")
    else println(maxi + " " + count)
  }
}

import java.util.Scanner

object CCorrectBraces extends App {

  val scanner = new Scanner(System.in)
  val input = scanner.next()

  var pointer = 0

  var max = 0
  var maxNum = 0

  start()

  if (max == 0) {
    println("0 1")
  } else {
    print(max + 1 + " ")
    println(maxNum)
  }

  def get: Char = input(pointer)

  def next: Char = {
    val res = get
    pointer += 1
    res
  }

  def eof(): Boolean = pointer >= input.size

  def start(): Unit = {
    while (!eof) {
      if (get == ')') next
      else parse()
    }
  }

  def parse(): Unit = {
    while (!eof && get == '(') {
      parseBraces()
    }
  }

  def parseBraces(): Unit = {
    if (!eof && get == '(') {
      val save = pointer
      next
      parse()
      if (!eof && get == ')') {
        recordResult(pointer - save)
        next
      } else if (!eof) {
        next
        parse()
      }
    }
  }

  def recordResult(item: Int): Unit = {
    if (max < item) {
      max = item
      maxNum = 1
    } else if (max == item) maxNum += 1
  }

}

import java.util.Scanner

object CCorrectBraces extends App {

  val scanner = new Scanner(System.in)
  val input = scanner.next()

  var pointer = 0

  var max = 0
  var maxNum = 0
  var streak = 0

  start()

  if (max == 0) {
    println("0 1")
  } else {
    print(max + " ")
    println(maxNum)
  }

  def get: Char = input(pointer)

  def next: Char = {
    val res = get
    pointer += 1
    res
  }

  def eof(): Boolean = pointer >= input.size

  def start(): Unit = {
    while (!eof) {
      if (get == ')')  {
        next
      }
      else parse()
    }
  }

  def parse(): Unit = {
    val save = pointer
    while (!eof && get == '(') {
      parseBraces()
    }
    if (pointer - save > 1) {
      recordResult(save)
    }
  }

  def parseBraces(): Unit = {
    if (!eof && get == '(') {
      val save = pointer
      next
      parse()
      if (!eof && get == ')') {
        //recordResult(save)
        next
      } else if (!eof) {
        next
        //parse()
      }
    }
  }

  def recordResult(save: Int): Unit = {
    val item = pointer - save
    if (max < item) {
      max = item
      maxNum = 1
    } else if (max == item) maxNum += 1
  }

}

import java.util.Scanner

object CCorrectBraces extends App {

  val scanner = new Scanner(System.in)
  val input = scanner.next()

  var pointer = 0

  var max = 0
  var maxNum = 0
  var streak = 0

  start()

  if (max == 0) {
    println("0 1")
  } else {
    print(max + 1 + " ")
    println(maxNum)
  }

  def get: Char = input(pointer)

  def next: Char = {
    val res = get
    pointer += 1
    res
  }

  def eof(): Boolean = pointer >= input.size

  def start(): Unit = {
    while (!eof) {
      if (get == ')')  {
        next
      }
      else parse()
    }
  }

  def parse(): Unit = {
    val save = pointer
    while (!eof && get == '(') {
      parseBraces()
    }
    if (pointer - save > 1) {
      recordResult(save)
    }
  }

  def parseBraces(): Unit = {
    if (!eof && get == '(') {
      val save = pointer
      next
      parse()
      if (!eof && get == ')') {
        //recordResult(save)
        next
      } else if (!eof) {
        next
        //parse()
      }
    }
  }

  def recordResult(save: Int): Unit = {
    val item = pointer - save
    if (max < item) {
      max = item
      maxNum = 1
    } else if (max == item) maxNum += 1
  }

}

object C5 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    val count = cu.Map.empty[Int, Int].withDefaultValue(0)
    var maxLen = 0
    var openCount = 0
    var currLen = 0
    var i = 0
    while (i < str.length) {
      if (str(i) == '(') {
        openCount += 1
        currLen += 1
      } else {
        if (openCount == 0) {
          count(currLen) += 1
          maxLen = math.max(maxLen, currLen)
          currLen = 0
        } else if (openCount > 0) {
          openCount -= 1
          currLen += 1
        }
      }
      i += 1
    }
    if (openCount == 0) {
      count(currLen) += 1
      maxLen = math.max(maxLen, currLen)
    }
    if (maxLen == 0) {
      out.println("0 1")
    } else {
      out.println(s"${maxLen} ${count(maxLen)}")
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


import java.util.Scanner

object cf270d extends App {
    val in = new Scanner(System.in)
	val (n, m) = (in.nextInt, in.nextInt)
	val input = (1 to n).map(i => (in.nextInt, in.nextFloat)._1)
	var dp = Array.fill(m + 1)(0)
	for (arri <- input)
		dp(arri) = 1 + dp.slice(1, arri + 1).max
	println(n - dp.max)
}

object cf270d extends App {
	val Array(n, m) = readLine.split(' ').map(_.toInt)
	val input = (1 to n).map(i => readLine.split(' ')).sortBy(_.apply(1).toFloat).map(_.apply(0).toInt)
	var dp = Array.fill(m + 1)(0)
	for (arri <- input)
		dp(arri) = 1 + dp.slice(1, arri + 1).max
	println(n - dp.max)
}

import java.util.Scanner

object cf270d extends App {
    val in = new Scanner(System.in)
	val (n, m) = (in.nextInt, in.nextInt)
	val input = (1 to n).map(i => (in.nextInt, in.nextFloat)).sortBy(_._2).map(_._1)
	var dp = Array.fill(m + 1)(0)
	for (arri <- input)
		dp(arri) = 1 + dp.slice(1, arri + 1).max
	println(n - dp.max)
}

object cf270d extends App {
	val Array(n, m) = readLine.split(' ').map(_.toInt)
	val input = (1 to n).map(i => readLine.split(' ').apply(0).toInt)
	var dp = Array.fill(m + 1)(0)
	for (arri <- input)
		dp(arri) = 1 + dp.slice(1, arri + 1).max
	println(n - dp.max)
}

object cf270d extends App {
  val Array(n, m) = readLine.split(' ').map(_.toInt)
  val input = (1 to n).map(i => readLine.split(' ').apply(0).toInt)
  var dp = Array.fill(n + 1)(0)
  var len = 0
  for (arri <- input) {
    var (l, r, ans) = (0, len, len)
    while (l <= r) {
      val m = (l + r) / 2
      if (dp(m) <= arri) {
        l = m + 1
        ans = m
      } else {
        r = m - 1
      }
    }
    dp(ans + 1) = arri
    if (ans >= len)
      len += 1
  }
  println(n - len)
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val f = new Array[Int](m)
    val g = new Array[Int](m)
    for (_ <- 1 to n) {
      val tokens = readLine().split(" ")
      var a = tokens(0).toInt - 1
      for (i <- m - 1 to a by -1) {
        f(i) = Math.min(f(i) + 1, f(a) + g(a) - g(i))
      }
      for (i <- a - 1 to 0 by -1) {
        g(i) += 1
      }
    }
    println(f(m - 1))
  }
}

object test6 extends App {
    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val s=(for(i<-1 to n) yield readLine.split(" ")(0).toInt) toArray
    val dp=Array.ofDim[Int](n+1,m+1)

    for(i<-n-1 to 0 by -1; j<-0 to m){
        dp(i)(j)=1+dp(i+1)(j)
        if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))
    }

    println(dp(0)(0))
}

object test6 extends App {
    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val s=(for(i<-1 to n) yield readLine.split(" ")(0).toInt).toArray
    val dp=Array.ofDim[Int](n+1,m+1)

    for(i<-n-1 to 0 by -1; j<-0 to m){
        dp(i)(j)=1+dp(i+1)(j)
        if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))
    }

    println(dp(0)(0))
}

object test6 extends App {
    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val s=new Array[Int](n)
    val x=new Array[Double](n)
    val dp=Array.ofDim[Int](n+1,m+1)
    for(i<-0 until n){
        val arr=readLine.split(" ")
        s(i)=arr(0).toInt
        x(i)=arr(1).toDouble
    }

    for(i<-n-1 to 0 by -1; j<-0 to m){
        dp(i)(j)=1+dp(i+1)(j)
        if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))
    }

    println(dp(0)(0))
}

object Main {
  def main(args: Array[String]) {
    val Array(n, _) = readLine().split(" ").map(_.toInt)
    var last = -1
    var count = 0
    for (_ <- 1 to n) {
      val tokens = readLine().split(" ")
      val s = tokens(0).toInt
      if (s < last) {
        count += 1
      }
      last = s
    }
    println(count)
  }
}


import scala.io.StdIn

object PracticeScala {
  def main(args: Array[String]): Unit = {
    var t = StdIn.readInt()
    while(t != 0){
      val n = StdIn.readInt()
      var i: Int = 0
      while(i < n){
        println("()" * i + "(" * (n - i) + ")" * (n - i) )
        i += 1
      }
      t -= 1
    }
  }
}

object A extends App {

  def brackets(n: Int): List[String] =
    (0 until n).foldLeft(List.empty[String]) { (brackets, i) =>
      val bracket = "(" * (n - 1) + ")" * i + "(" + ")" * (n - i)
      bracket :: brackets
    }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()

    out.println(brackets(n).mkString("\n"))
    out.flush()
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Sorting.quickSort
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {
        while (!st.hasMoreTokens) {
            st = new StringTokenizer(reader.readLine())
        }
        st.nextToken()
    }

    def readInt() = next.toInt
    def readLong() = next.toLong
    def readString() = next()

    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 main(args: Array[String]) {
        var t = readInt()
        while (t > 0) {
            t -= 1
            val n = readInt()
            val m = (1L << n) - 1
            val a = new Array[Int](2*n)
            for (i <- 0 until n) {
                for (k <- 0 until n) {
                    a(n - k - 1) = (((m - i) >> k ) & 1).toInt
                    a(k + n) = 1 - a(n - k - 1)
                }

                for (i <- 0 until 2*n) {
                    if (a(i) == 1) writer.print("(")
                    else writer.print(")")
                }
                writer.println()
            }
        }
        writer.close()
    }
}

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

object test {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    def main(args: Array[String]): Unit = {
        val t = readInt()
        for (tt <- 1 to t) {
            val n = readInt()
            for (i <- 1 to n) {
                for (j <- 1 to i)
                    writer.print('(')
                for (j <- 1 to i)
                    writer.print(')')
                for (j <- 1 to n-i)
                    writer.print("()")
                writer.println()
            }
            writer.flush()
        }
    }
}


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

  val t = readInt()

  private def check(r: Long, g: Long, b: Long, w: Long): Boolean =
    r >= 0 && g >= 0 && b >= 0 && List(r, g, b, w).foldLeft(0L)(_ + _ % 2) <= 1

  (0 until t).foreach { _ =>
    val Array(r, g, b, w) = readLine().split(" ").map(_.toLong)

    val ans = check(r, g, b, w) || check(r - 1, g - 1, b - 1, w + 3)

    if (ans) println("Yes") else println("No")
  }
}

import scala.io.StdIn._

object taskA extends App {

  def singleCheck(input: Array[Int]): Boolean = {
    input.foreach { x =>
      if (x < 0)
        return false
    }
    if (input(3) % 2 == 0) {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 <= 1)
        true
      else
        false
    } else {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)
        true
      else
        false
    }
  }
4

  def check(input: Array[Int]): String = {
    var res: Boolean = false
    if (singleCheck(input)) res = true
    else {
      val newInput = input.map(x => x - 1)
      newInput(3) += 4
      res = singleCheck(newInput)
    }
    if (res) "Yes" else "No"
  }

  //READING THE STANDARD INPUT
  val sets = readInt

  var lst: List[String] = List()
  (1 to sets).foreach { _ =>
    val input: Array[Int] = readLine.split(" ").map(_.toInt)
    //println(check(input))
    lst = lst ::: List(check(input))
  }

  lst.foreach { x =>
    println(x)
  }

}

object A 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 r = in.nextInt()
      val g = in.nextInt()
      val b = in.nextInt()
      val w = in.nextInt()

      val count = (r % 2) + (g % 2) + (b % 2) + (w % 2)
      if (count == 0 || count == 1) {
        println("Yes")
      } else {
        val c2 = (r % 2) + (g % 2) + (b % 2)
        if (r != 0 && g != 0 && b != 0) {
          if (w % 2 == 1) {
            if (c2 >= 2) println("Yes") else println("No")
          } else {
            if (c2 == 1 || c2 == 3) println("Yes") else println("No")
          }
        } else {
          println("No")
        }
      }
    }
  }

  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 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.io.StdIn._

object taskA extends App {

  def singleCheck(input: Array[Int]): Boolean = {
    input.foreach { x =>
      if (x < 0)
        return false
    }
    if (input(3) % 2 == 0) {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 <= 1)
        true
      else
        false
    } else {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)
        true
      else
        false
    }
  }
4

  def check(input: Array[Int]): String = {
    var res: Boolean = false
    if (singleCheck(input)) res = true
    else res = singleCheck(input.map(x => x - 1))
    if (res) "Yes" else "No"
  }

  //READING THE STANDARD INPUT
  val sets = readInt

  var lst: List[String] = List()
  (1 to sets).foreach { _ =>
    val input: Array[Int] = readLine.split(" ").map(_.toInt)
    //println(check(input))
    lst = lst ::: List(check(input))
  }

  lst.foreach { x =>
    println(x)
  }

}

import scala.io.StdIn._

object taskA extends App {

  def singleCheck(input: Array[Int]): Boolean = {
    input.foreach { x =>
      if (x < 0)
        return false
    }
    if (input(3) % 2 == 0) {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 1)
        true
      else
        false
    } else {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)
        true
      else
        false
    }
  }

  def check(input: Array[Int]): String = {
    var res: Boolean = false
    if (singleCheck(input)) res = true
    else res = singleCheck(input.map(x => x - 1))
    if (res) "Yes" else "No"
  }

  //READING THE STANDARD INPUT
  val sets = readInt

  var lst: List[String] = List()
  (1 to sets).foreach { _ =>
    val input: Array[Int] = readLine.split(" ").map(_.toInt)
    //println(check(input))
    lst = lst ::: List(check(input))
  }

  lst.foreach { x =>
    println(x)
  }

}


import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val ss = Array.fill(n){ readLine.toCharArray }

  var max = 0

  for (a <- 'a' to 'z') {
    for (b <- 'a' to 'z') if (b != a) {
      var sum = 0
      for (i <- 0 until n) {
        var ok = true
        for (c <- ss(i)) {
          if (c != a && c != b) ok = false
        }
        if (ok) {
          sum += ss(i).length
        }
      }
      if (sum > max) {
        max = sum
      }
    }
  }

  println(max)
}

//package round329.a

import java.util.Scanner

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

  val n = sc.nextInt
  sc.nextLine
  val words = (1 to n).map(_ => sc.nextLine())

//  println(words)

  val goodWords = words.filter { word =>
    val grouped = word.toList.groupBy(c => c)
    grouped.keys.size <= 2
  }

  var best = 0

  def containsOnly(s: String, allowed: List[Char]): Boolean = {
    s.forall(c => allowed.contains(c))
  }

//  println(goodWords)

  ('a' to 'z').foreach { char1 =>
    ('a' to 'z').foreach { char2 =>
      val wrds = goodWords.filter(w => containsOnly(w, List(char1, char2)))
      val payment = wrds.map(_.length).sum
//      println(s"trying $char1, $char2: $payment")
      best = Math.max(best, payment)
    }
  }

  println(best)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var map = ('a' to 'z').flatMap { i =>
    (i to 'z').map(j => "" + i + j -> 0)
  }.toMap
  (1 to n).foreach {_ =>
      val str = in.next()
      val distinct = str.distinct
      if (distinct.length == 2) {
        val key = distinct.sorted
        map +=  (key -> (map(key) + str.length))
      } else if (distinct.length == 1) {
        ('a' to 'z').foreach { j =>
          val key = (distinct + j).sorted
          map += (key -> (map(key) + str.length))
        }
      }
  }
  println(map.values.max)
}

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

object A {

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

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

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val words = new Array[String](n)
    for (i <- 0 until n)
      words(i) = next
    var max = 0
    for (c1 <- 'a' to 'z') {
      for (c2 <- 'a' to 'z') {
        if (c1 != c2) {
          var len = 0
          for (i <- 0 until n) {
            var flag = true
            for (j <- 0 until words(i).toCharArray.length) {
              if (words(i).toCharArray().apply(j) != c1 && words(i).toCharArray().apply(j) != c2)
                flag = false
            }
            if (flag) {
              len += words(i).toCharArray.length
            }
          }
          max = Math.max(max, len)
        }
      }
    }
    out.println(max)
    return 0
  }
}

import scala.annotation.tailrec
import scala.collection.immutable.IndexedSeq
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

object _593A extends CodeForcesApp {
  import CodeForcesApp._
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val words = Seq.fill(n)(next())

    val all: IndexedSeq[((Char, Char), String)] = for {
      i <- 'a' to 'z'
      j <- 'a' to 'z'
      w <- words
      t = w.replace(i.toString, "").replaceAll(j.toString, "")
      if t.isEmpty
    } yield (i, j) -> w

    val map = all.groupBy(_._1).mapValues(_.map(_._2.length).sum)
    if (map.isEmpty) 0 else map.values.max
  }

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(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))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  private[this] val tokenizers = lines.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
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  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() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}


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

object P408A extends App {

  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val K = Array.fill(N)(sc.nextInt)
  val slurpQueue: Int => List[Int] = i => List.fill(K(i))(sc.nextInt)
  val Q = List.tabulate(N)(slurpQueue)
  val stopTime: List[Int] => Int = { lst => lst.sum * 5 + lst.size * 15 }
  val res = Q.map(stopTime).min

  out.println(res)
  out.close
}

object A extends App {

  def calc(in:Array[Int]): Int = {
    in.sum * 5 + in.length*15
  }

  var ans = (1<<30)
  val n = readInt()
  val t = readLine()
  for (i <- 0 until n) {
    val line = readLine()
    val in:Array[Int]  = line.split(" ") map (_.toInt)
    ans = ans min calc(in)
  }
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val k = in.next().split(" ").map(_.toInt)
  val p = (1 to n).map(_ => in.next().split(" ").map(_.toInt))
  val res = p.map(t => t.sum * 5 + t.length * 15)
  println(res.min)
}

object A408 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val k = readInts(n)
    val m = k.map(readInts)
    println(m.map(a => a.sum*5 + a.length*15).min)
  }

  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))
    }
  }

}

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A408 extends App {

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val k: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var min: Int = Int.MaxValue
    for (i <- 0 until n) {
      val m: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val latency = m.map(bucket => bucket * 5 + 15).sum
      min = Math.min(min, latency)
    }
    println(min)
  }

  solve()

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val k = in.next().split(" ").map(_.toInt)
  val p = (1 to n).map(_ => in.next().split(" ").map(_.toInt))
  val res = p.map(t => t.sum * 5 + t.length * 15)
  println(res.zipWithIndex.min._2 + 1)
}

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

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

  type Cards = List[Int]
  val CS: Cards = List.fill(N)(sc.nextInt)

  def solve(): Unit = {

    @tailrec
    def loop(spt: Int, dpt: Int, turn: Int, cs: Cards, rcs: Cards): Unit = {
      if (turn == N) out.println(List(spt, dpt).mkString(" "))
      else (cs, rcs) match {
        case (x :: xs, y :: ys) if x > y => if (turn % 2 == 0) loop(spt + x, dpt, turn + 1, xs, rcs)
                                            else loop(spt, dpt + x, turn + 1, xs, rcs)
        case (_, y :: ys) => if (turn % 2 == 0) loop(spt + y, dpt, turn + 1, cs, ys)
                             else loop(spt, dpt + y, turn + 1, cs, ys)
      }
    }

    loop(0, 0, 0, CS, CS.reverse)
  }

  solve
  out.close
}

object A extends App {

  def calc(in:Array[Int]): Int = {
    in.sum * 5 + in.length*15
  }

  var ans = (1<<30)
  val n = readInt()
  for (i <- 0 until n) {
    val line = readLine()
    val in:Array[Int]  = line.split(" ") map (_.toInt)
    ans = ans min calc(in)
  }
  println(ans)
}


object CF291B extends App {
  val Array(n, x, y) = readLine().split(" ").map(_.toInt)

  val ax = new Array[Int](n)
  val ay = new Array[Int](n)

  val shot = new Array[Boolean](n)

  (0 until n) foreach { i =>
    shot(i) = false
    val Array(tx, ty) = readLine().split(" ").map(_.toInt)
    ax(i) = tx
    ay(i) = ty
  }

  var res = 0
  (0 until n) foreach { i =>
    if (!shot(i)) {
      res += 1
      (0 until n) foreach { j =>
        if ((y - ay(i)) * (x - ax(j)) == (y - ay(j)) * (x - ax(i))) shot(j) = true
      }
    }
  }

  print(res)
}

object B514 {

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

  def sameLine(x: Int, y: Int, x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {
    (x-x1)*(y-y2) == (x-x2)*(y-y1)
  }

  def main(args: Array[String]): Unit = {
    val Array(n, x0, y0) = readInts(3)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))
    val vis = Array.fill(n)(false)
    def dfs(a: Int): Unit = {
      vis(a) = true
      for(i <- 0 until n if !vis(i)) {
        if(sameLine(x0, y0, in(a)._1, in(a)._2, in(i)._1, in(i)._2))
          vis(i) = true
      }
    }
    var res = 0
    for(i <- 0 until n) {
      if(!vis(i)) {
        dfs(i)
        res += 1
      }
    }
    println(res)
  }

  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 scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Double, Int]
    var undef = 0

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      if (p1-x != 0 ) {
        val slope = (p2 - y) / (p1 - x).toDouble
        if (!map.contains(slope)) {
          map.put(slope, 1)
        }
      } else {
        undef = 1
      }
    }

    println(map.size + undef)
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Int, Int]

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      val slope = if ((p1-x) == 0) 0 else math.abs((p2-y)/(p1-x))
      if (!map.contains(slope))
        map.put(slope, 1)
    }

    println(map.size)
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Int, Int]
    var undef = 0

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      if (p1-x != 0 ) {
        val slope = (p2 - y) / (p1 - x)
        if (!map.contains(slope)) {
          map.put(slope, 1)
        }
      } else {
        undef = 1
      }
    }

    println(map.size + undef)
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Int, Int]
    var undef = 0

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      if (p1-x != 0 ) {
        val slope = math.abs ((p2 - y) / (p1 - x))
        if (!map.contains(slope)) {
          map.put(slope, 1)
        }
      } else {
        undef = 1
      }
    }

    println(map.size + undef)
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Int, Int]

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      val slope = if ((p1-x) == 0) 0 else (p2-y)/(p1-x)
      if (!map.contains(slope))
        map.put(slope, 1)
    }

    println(map.size)
  }

}


object C extends App {

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

  val Array(n) = readInts(1)

  val checked = Array.fill('z' - 'a' + 1)(false)
  var res = 0

  for (_ <- 0 until n) {
    //println(checked.count(_ == false))
    val solved = checked.count(_ == false) == 1
    readLine.split(" ") match {

      case Array(".", w) =>
        for (c <- w) checked(c - 'a') = true

      case Array("!", w) =>
        if (solved) res += 1
        val bad = w.toSet
        for (c <- 'a' to 'z') if (!bad(c)) checked(c - 'a') = true

      case Array("?", s) =>
        if (solved) res += 1
        checked(s.head - 'a') = true
    }
  }

  println(Math.max(0, res - 1))
}

import java.util

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

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    var excessiveCount = 0
    var poss = new mutable.HashSet[Char]()
    (0 until 26).map('a' + _).map(_.asInstanceOf[Char]).foreach(c => poss.add(c))
    var step = 0
    while (step < n) {
      val Array(cmd, wd) = StdIn.readLine().split(" ")
      cmd match {
        case "!" =>
          if (poss.size <= 1) {
            excessiveCount += 1
          }
          poss = poss.intersect(wd.toSet)
        case "." => poss = poss.diff(wd.toSet)
        case "?" =>
          if (poss.size <= 1 && step != n - 1) {
            excessiveCount += 1
          }
          poss.remove(wd(0))
      }
      step += 1
    }
    println(excessiveCount)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

}