You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).

The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.

Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.

NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA".

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter

object CF550A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

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

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

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

  def main(args: Array[String]): Unit = {
    val in = new InputReader(System.in)
    var s = in.next()
    val ok = solve(s,"AB","BA") || solve(s,"BA","AB")
    if ( ok ) print("YES")
    else print("NO")
  }

  def solve(ss: String, a: String, b:String ): Boolean =  {
    var s = ss
    if ( s.indexOf(a) != -1)
      s = s.replaceFirst(a, "XX")
    else return false;
    if ( s.indexOf(b) != -1)
      return true;
    else return false
  }
}

import scala.io.StdIn._

object A extends App {
  val s = readLine().toCharArray

  def find(): String = {
    var AB = false
    var BA = false

    var i = 0
    while (i < s.length - 1) {
      if (!AB && s(i) == 'A' && s(i + 1) == 'B') {
        AB = true
        i += 1
      }
      else if (!AB && i < s.length - 2 && s(i + 1) == 'A' && s(i + 2) == 'B') {
        AB = true
        i += 2
      }
      else if (!BA && s(i) == 'B' && s(i + 1) == 'A') {
        BA = true
        i += 1
      }

      if (AB && BA) {
        return "YES"
      }

      i += 1
    }

    AB = false
    BA = false

    i = 0
    while (i < s.length - 1) {
      if (!BA && s(i) == 'B' && s(i + 1) == 'A' ) {
        BA = true
        i += 1
      }
      else if (!BA && i < s.length - 2 && s(i + 1) == 'B' && s(i + 2) == 'A') {
        BA = true
        i += 2
      }
      else if (!AB && s(i) == 'A' && s(i + 1) == 'B') {
        AB = true
        i += 1
      }

      if (AB && BA) {
        return "YES"
      }

      i += 1
    }

    "NO"
  }

  println(find())
}

object Solution extends App {

    val input = scala.io.StdIn.readLine()
    val reverseInput = input.reverse
    val inputSize = input.size
    val enough = input.contains("AB") && input.contains("BA")
    val abFirst = input.indexOf("AB") + 1 < inputSize - reverseInput.indexOf("AB") - 2
    val baFirst = input.indexOf("BA") + 1 < inputSize - reverseInput.indexOf("BA") - 2
    if (enough && (abFirst || baFirst)) {
        println("YES")
    } else {
        println("NO")
    }
}

object Solution extends App {

    val input = scala.io.StdIn.readLine()

    val enough = input.contains("AB") && input.contains("BA")
    val abFirst = input.indexOf("AB") + 1 < input.lastIndexOf("BA")
    val baFirst = input.indexOf("BA") + 1 < input.lastIndexOf("AB")

    if (enough && (abFirst || baFirst)) {
        println("YES")
    } else {
        println("NO")
    }
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter

object CF550A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

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

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

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

  def main(args: Array[String]): Unit = {
    val in = new InputReader(System.in)
    var s = in.next()
    if ( s.indexOf("AB") != -1)
      s = s.replaceFirst("AB", "")
    else return "NO"
    if ( s.indexOf("BA") != -1)
      return "YES"
    else return "NO"

  }
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter

object CF550A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

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

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

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

  def main(args: Array[String]): Unit = {
    println(solve)
  }

  def solve : String =  {
    val in = new InputReader(System.in)
    var s = in.next()
    if ( s.indexOf("AB") != -1)
      s = s.replaceFirst("AB", "")
    else return "NO"
    if ( s.indexOf("BA") != -1)
      return "YES"
    else return "NO"
  }
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter

object CF550A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

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

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

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

  def main(args: Array[String]): Unit = {
    println(solve)
  }

  def solve : String =  {
    val in = new InputReader(System.in)
    var s = in.next()
    if ( s.indexOf("AB") != -1)
      s = s.replaceFirst("AB", "XX")
    else return "NO"
    if ( s.indexOf("BA") != -1)
      return "YES"
    else return "NO"
  }
}

import scala.io.StdIn._

object A extends App {
  val s = readLine().toCharArray

  def find(): String = {
    var AB = false
    var BA = false

    for (i <- 0 until s.length - 1) {
      if (!AB && s(i) == 'A' && s(i + 1) == 'B') AB = true
      else if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true
      else if (AB && BA) {
        return "YES"
      }
    }

    AB = false
    BA = false

    for (i <- 0 until s.length - 1) {
      if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true
      else if (!BA && s(i) == 'A' && s(i + 1) == 'B') AB = true
      else if (AB && BA) {
        return "YES"
      }
    }

    "NO"
  }

  println(find())
}

import scala.io.StdIn._

object A extends App {
  val s = readLine().toCharArray

  def find(): String = {
    var AB = false
    var BA = false

    var i = 0
    while (i < s.length - 1) {
      if (!AB && s(i) == 'A' && s(i + 1) == 'B') {
        AB = true
        i += 1
      }
      else if (!BA && s(i) == 'B' && s(i + 1) == 'A') {
        BA = true
        i += 1
      }

      if (AB && BA) {
        return "YES"
      }

      i += 1
    }

    AB = false
    BA = false

    i = 0
    while (i < s.length - 1) {
      if (!BA && ((s(i) == 'B' && s(i + 1) == 'A') || (i < s.length - 2 && s(i + 1) == 'B' && s(i + 2) == 'A'))) {
        BA = true
        i += 1
      }
      else if (!AB && s(i) == 'A' && s(i + 1) == 'B') {
        AB = true
        i += 1
      }

      if (AB && BA) {
        return "YES"
      }

      i += 1
    }

    "NO"
  }

  println(find())
}

import scala.io.StdIn._

object A extends App {
  val s = readLine().toCharArray

  def find(): String = {
    var AB = false
    var BA = false

    var i = 0
    while (i < s.length - 1) {
      if (!AB && s(i) == 'A' && s(i + 1) == 'B') {
        AB = true
        i += 1
      }
      else if (!BA && s(i) == 'B' && s(i + 1) == 'A') {
        BA = true
        i += 1
      }

      if (AB && BA) {
        return "YES"
      }

      i += 1
    }

    AB = false
    BA = false

    i = 0
    while (i < s.length - 1) {
      if (!BA && s(i) == 'B' && s(i + 1) == 'A') {
        BA = true
        i += 1
      }
      else if (!AB && s(i) == 'A' && s(i + 1) == 'B') {
        AB = true
        i += 1
      }

      if (AB && BA) {
        return "YES"
      }

      i += 1
    }

    "NO"
  }

  println(find())
}

import scala.io.StdIn._

object A extends App {
  val s = readLine().toCharArray

  def find(): String = {
    var AB = false
    var BA = false

    var i = 0
    while (i < s.length - 1) {
      if (!AB && s(i) == 'A' && s(i + 1) == 'B') {
        AB = true
        i += 1
      }
      else if (!BA && s(i) == 'B' && s(i + 1) == 'A') {
        BA = true
        i += 1
      }

      if (AB && BA) {
        return "YES"
      }

      i += 1
    }

    AB = false
    BA = false

    i = 0
    while (i < s.length - 1) {
      if (!BA && s(i) == 'B' && s(i + 1) == 'A' ) {
        BA = true
        i += 1
      }
      else if (i < s.length - 2 && s(i + 1) == 'B' && s(i + 2) == 'A') {
        BA = true
        i += 2
      }
      else if (!AB && s(i) == 'A' && s(i + 1) == 'B') {
        AB = true
        i += 1
      }

      if (AB && BA) {
        return "YES"
      }

      i += 1
    }

    "NO"
  }

  println(find())
}

import scala.io.StdIn._

object A extends App {
  val s = readLine().toCharArray

  var AB = false
  var BA = false

  def find(): String = {
    for (i <- 0 until s.length - 1) {
      if (!AB && s(i) == 'A' && s(i + 1) == 'B') AB = true
      else if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true
      else if (AB && BA) {
        return "YES"
      }
    }

    for (i <- 0 until s.length - 1) {
      if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true
      else if (!BA && s(i) == 'A' && s(i + 1) == 'B') AB = true
      else if (AB && BA) {
        return "YES"
      }
    }

    "NO"
  }

  println(find())
}

import scala.io.StdIn._

object A extends App {
  val s = readLine().toCharArray

  def find(): String = {
    var AB = false
    var BA = false

    for (i <- 0 until s.length - 1) {
      if (!AB && s(i) == 'A' && s(i + 1) == 'B') AB = true
      else if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true

      if (AB && BA) {
        return "YES"
      }
    }

    AB = false
    BA = false

    for (i <- 0 until s.length - 1) {
      if (!BA && s(i) == 'B' && s(i + 1) == 'A') BA = true
      else if (!AB && s(i) == 'A' && s(i + 1) == 'B') AB = true

      if (AB && BA) {
        return "YES"
      }
    }

    "NO"
  }

  println(find())
}

object Solution extends App {

    val input = scala.io.StdIn.readLine()
    val reverseInput = input.reverse
    val inputSize = input.size

    if (input.indexOf("AB") + 1 < inputSize - reverseInput.indexOf("AB") - 2) {
        println("YES")
    } else if (input.indexOf("BA") + 1 < inputSize - reverseInput.indexOf("BA") - 2) {
        println("YES")
    } else {
        println("NO")
    }
}


Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.

The first line contains three space-separated integers n, m and d (1 ≤ m ≤ n ≤ 100000; 0 ≤ d ≤ n - 1). The second line contains m distinct space-separated integers p1, p2, ..., pm (1 ≤ pi ≤ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.

Print a single number — the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.

NoteSample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1) ++ readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a).append(b)
    edges(b).append(a)
  }

  def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size)(0)
    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def shortestPathsTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        shortestPathsTR()
      }
    }

    shortestPathsTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

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

  val marked = new mutable.BitSet(n + 1)
  marked ++= readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) { // BFS
      val next = toVisit.dequeue
      for (succ <- graph(next); if !visited(succ)) {
        toVisit += succ
        visited += succ
      }
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) { // BFS
      val next = toVisit.dequeue
      for (succ <- graph(next); if !visited(succ)) {
        toVisit += succ
        visited += succ
        dists(succ) = dists(next) + 1
      }
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readInts0 = readString.split(' ').map(_.toInt)
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

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

  val marked = new mutable.BitSet(n + 1) ++= readInts0 //(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    /*val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt*/
    val Array(a, b) = readInts0
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1) ++ readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val Array(a, b) = readInts(2)
    edges(a).append(b)
    edges(b).append(a)
  }

  def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size)(0)
    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def shortestPathsTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        shortestPathsTR()
      }
    }

    shortestPathsTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val st = tokenizeLine; Array.fill(n)(st.nextToken().toInt) }

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1) ++ readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int](2))

  for (i <- 0 until n - 1) {
    val Array(a, b) = readInts(2)
    edges(a).append(b)
    edges(b).append(a)
  }

  def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size)(0)
    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def shortestPathsTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        shortestPathsTR()
      }
    }

    shortestPathsTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

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

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

  val marked = new mutable.BitSet(n + 1)
  marked ++= readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readInts0 = readString.split(' ').map(_.toInt)
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

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

  val marked = new mutable.BitSet(n + 1) ++= readInts0 //(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1)
  val st = tokenizeLine
  for (i <- 0 until m) marked += st.nextToken.toInt

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a).append(b)
    edges(b).append(a)
  }

  def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size)(0)
    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def shortestPathsTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        shortestPathsTR()
      }
    }

    shortestPathsTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

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

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

  val marked = new mutable.BitSet(n + 1)
  marked ++= readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) { // BFS
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) { // BFS
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

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

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

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

  val marked = new mutable.BitSet(n + 1)
  marked ++= readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) { // BFS
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) { // BFS
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val _fromA = scala.actors.Futures.future(shortestPaths(edges, a))
  val _fromB = scala.actors.Futures.future(shortestPaths(edges, b))
  val fromA = _fromA()
  val fromB = _fromB()

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)

  Console.flush
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

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

  val marked = new mutable.BitSet(n + 1) ++= readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1) ++ readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    //val Array(a, b) = readInts(2)
    val (a, b) = (st.nextToken.toInt, st.nextToken.toInt)
    edges(a).append(b)
    edges(b).append(a)
  }

  def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size)(0)
    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def shortestPathsTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        shortestPathsTR()
      }
    }

    shortestPathsTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

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

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

  val marked = new mutable.BitSet(n + 1)
  marked ++= readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    //visited += source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    //visited += source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

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

  val marked = new mutable.BitSet(n + 1)
  marked ++= readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) { // BFS
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size)
    visited += source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) { // BFS
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

//  val _fromA = scala.actors.Futures.future(shortestPaths(edges, a))
//  val _fromB = scala.actors.Futures.future(shortestPaths(edges, b))
//  val fromA = _fromA()
//  val fromB = _fromB()

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  def prof(i: Int) = if (m == 17585) println(i + ": " + (System.currentTimeMillis() - executionStart) + " ms")

  val Array(n, m, d) = readInts(3)
  prof(1)
  val marked = new mutable.BitSet(n + 1) ++= readInts(m)
  prof(2)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())
  prof(3)

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a).append(b)
    edges(b).append(a)
  }
  prof(4)

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)
  prof(5)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)
  prof(6)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)
  prof(7)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  def prof(i: Int) = if (m == 17585) println(i + ": " + (System.currentTimeMillis() - executionStart) + " ms")

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1)
  prof(1)
  val st = tokenizeLine
  for (i <- 0 until m) marked += st.nextToken.toInt
  prof(2)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())
  prof(3)

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a).append(b)
    edges(b).append(a)
  }
  prof(4)

  def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size)(0)
    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def shortestPathsTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        shortestPathsTR()
      }
    }

    shortestPathsTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)
  prof(5)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)
  prof(6)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)
  prof(7)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val st = tokenizeLine; Array.tabulate(n)(i => st.nextToken().toInt) }

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1) ++ readInts(m)

  val edges = Array.fill(n + 1)(mutable.Seq[Int]())
println("read1")

  for (i <- 0 until n - 1) {
    val Array(a, b) = readInts(2)
    edges(a) :+= b
    edges(b) :+= a
  }
println("read2")
  def traverseFrom(graph: Array[mutable.Seq[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def shortestPaths(graph: Array[mutable.Seq[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size)(0)
    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def shortestPathsTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        shortestPathsTR()
      }
    }

    shortestPathsTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

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

  val Array(n, m, d) = readInts
  val marked = new mutable.BitSet(n + 1)
  readInts.foreach(marked += _)

  val edges = Array.fill(n + 1)(mutable.ArrayBuffer[Int]())

  for (i <- 0 until n - 1) {
    val Array(a, b) = readInts
    edges(a) :+= b
    edges(b) :+= a
  }

  if (m == 21456) println("read")

  def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size + 1)
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        visited ++= succ
        toVisit ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def sssp(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size + 1)(0)
    val visited = new mutable.BitSet(graph.size + 1)
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def ssspTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        ssspTR()
      }
    }

    ssspTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = sssp(edges, a)
  val fromB = sssp(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

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

  val Array(n, m, d) = readInts
  val marked = new mutable.BitSet(n + 1)
  readInts.foreach(marked += _)

  val edges = mutable.ArrayBuffer.fill(n + 1, 0)(0)

  for (i <- 0 until n - 1) {
    val Array(a, b) = readInts
    edges(a) :+= b
    edges(b) :+= a
  }

  if (m == 21456) println("read")

  def traverseFrom(graph: mutable.ArrayBuffer[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size + 1)
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        visited ++= succ
        toVisit ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def sssp(graph: mutable.ArrayBuffer[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size + 1)(0)
    val visited = new mutable.BitSet(graph.size + 1)
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def ssspTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        ssspTR()
      }
    }

    ssspTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = sssp(edges, a)
  val fromB = sssp(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

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

  val Array(n, m, d) = readInts
  val marked = readInts.toSet

  val edges = Array.fill(n + 1)(mutable.Seq[Int]())

  for (i <- 0 until n - 1) {
    val Array(a, b) = readInts
    edges(a) :+= b
    edges(b) :+= a
  }

  @annotation.tailrec
  def traverseTR(graph: Array[mutable.Seq[Int]], toVisit: Seq[Int], visited: Set[Int], accumulator: Option[Int]): Option[Int] = {
    if (toVisit.isEmpty) {
      accumulator
    } else {
      val next = toVisit.head
      val succ = (graph(next).toSet -- visited -- toVisit).toSeq
      // DFS :
      //traverseTR(graph, succ ++ toVisit.tail, visited + next, accumulator :+ next)
      // BFS :
      traverseTR(graph, toVisit.tail ++ succ, visited + next, if (marked(next)) Some(next) else accumulator)
    }
  }

  @annotation.tailrec
  def sssp(graph: Array[mutable.Seq[Int]], toVisit: Seq[Int], visited: Set[Int], curDist: Int, dists: Array[Int]): Unit = {
    if (!toVisit.isEmpty) {
      val next = toVisit.head
      val succ = (graph(next).toSet -- visited -- toVisit).toSeq
      for (s <- succ) dists(s) = curDist
      sssp(graph, toVisit.tail ++ succ, visited + next, curDist + 1, dists)
    }
  }

  def traverseFrom(graph: Array[mutable.Seq[Int]], initial: Int) =
    traverseTR(graph, Seq(initial), Set.empty, None)

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = Array.ofDim[Int](n + 1)
  val fromB = Array.ofDim[Int](n + 1)

  sssp(edges, Seq(a), Set.empty, 1, fromA)
  sssp(edges, Seq(b), Set.empty, 1, fromB)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val st = tokenizeLine; Array.tabulate(n)(i => st.nextToken().toInt) }

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1) ++ readInts(m)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int](2))
if (m == 21456 ) println("read1")

  for (i <- 0 until n - 1) {
    val Array(a, b) = readInts(2)
    edges(a).append(b)
    edges(b).append(a)
  }
if (m == 21456 ) println("read2")
  def traverseFrom(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def traverseTR(accumulator: Option[Int]): Option[Int] = {
      if (toVisit.isEmpty) {
        accumulator
      } else {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        traverseTR(if (marked(next)) Some(next) else accumulator)
      }
    }

    traverseTR(None)
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val dists = Array.fill(graph.size)(0)
    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)

    @annotation.tailrec
    def shortestPathsTR(): Unit = {
      if (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        for (s <- succ) dists(s) = dists(next) + 1
        shortestPathsTR()
      }
    }

    shortestPathsTR()
    dists
  }

  val a = traverseFrom(edges, 1).get
  val b = traverseFrom(edges, a).getOrElse(a)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  def prof(i: Int) = if (m == 17585) println(i + ": " + (System.currentTimeMillis() - executionStart) + " ms")

  val Array(n, m, d) = readInts(3)
  prof(1)
  val marked = new mutable.BitSet(n + 1) ++= readInts(m)
  prof(2)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())
  prof(3)

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) += b
    edges(b) += a
  }
  prof(4)

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)
  prof(5)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)
  prof(6)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)
  prof(7)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  def prof(i: Int) = if (m == 17585) println(i + ": " + (System.currentTimeMillis() - executionStart) + " ms")

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1)
  prof(1)
  val st = tokenizeLine
  for (i <- 0 until m) marked += st.nextToken.toInt
  prof(2)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())
  prof(3)

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a).append(b)
    edges(b).append(a)
  }
  prof(4)

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
        val next = toVisit.dequeue
        val succ = graph(next).filter(!visited(_))
        toVisit ++= succ
        visited ++= succ
        if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)
  prof(5)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)
  prof(6)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)
  prof(7)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  def prof(i: Int) = if (m == 17585) println(i + ": " + (System.currentTimeMillis() - executionStart) + " ms")

  val Array(n, m, d) = readInts(3)
  val marked = new mutable.BitSet(n + 1)
  prof(1)
  marked ++= readInts(m)
  //val st = tokenizeLine
  //for (i <- 0 until m) marked += st.nextToken.toInt
  prof(2)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())
  prof(3)

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a).append(b)
    edges(b).append(a)
  }
  prof(4)

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)
  prof(5)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)
  prof(6)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)
  prof(7)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  def prof(i: Int) = if (m == 17585) println(i + ": " + (System.currentTimeMillis() - executionStart) + " ms")

  val Array(n, m, d) = readInts(3)
  prof(1)
  val marked = new mutable.BitSet(n + 1) ++= readInts(m)
  prof(2)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())
  prof(3)

  for (i <- 0 until n - 1) {
    /*val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt*/
    val Array(a, b) = readInts(2)
    edges(a).append(b)
    edges(b).append(a)
  }
  prof(4)

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)
  prof(5)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)
  prof(6)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)
  prof(7)

  println(result)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)

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

  def prof(i: Int) = if (m == 17585) println(i + ": " + (System.currentTimeMillis() - executionStart) + " ms")

  val Array(n, m, d) = readInts(3)
  prof(1)
  val marked = new mutable.BitSet(n + 1) ++= readInts(m)
  prof(2)

  val edges = Array.fill(n + 1)(new mutable.ArrayBuffer[Int]())
  prof(3)

  for (i <- 0 until n - 1) {
    val st = tokenizeLine
    val a = st.nextToken.toInt
    val b = st.nextToken.toInt
    edges(a) :+= b
    edges(b) :+= a
  }
  prof(4)

  def remoteVertex(graph: Array[mutable.ArrayBuffer[Int]], source: Int) = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    var remote: Option[Int] = None

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      if (marked(next)) remote = Some(next)
    }

    remote
  }

  def shortestPaths(graph: Array[mutable.ArrayBuffer[Int]], source: Int): Array[Int] = {

    val visited = new mutable.BitSet(graph.size) + source
    val toVisit = mutable.Queue(source)
    val dists = Array.fill(graph.size)(0)

    while (!toVisit.isEmpty) {
      val next = toVisit.dequeue
      val succ = graph(next).filter(!visited(_))
      toVisit ++= succ
      visited ++= succ
      for (s <- succ) dists(s) = dists(next) + 1
    }

    dists
  }

  val a = remoteVertex(edges, 1).get
  val b = remoteVertex(edges, a).getOrElse(a)
  prof(5)

  val fromA = shortestPaths(edges, a)
  val fromB = shortestPaths(edges, b)
  prof(6)

  val result = (1 to n).count(i => fromA(i) <= d && fromB(i) <= d)
  prof(7)

  println(result)
}


Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 \dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index $$$i$$$ ($$$1 \leq i \leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c \neq s_i$$$.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains a single string $$$s$$$ ($$$1 \leq |s| \leq 50$$$) consisting of lowercase English letters.

For each test case, print the final string in a single line.

NoteIn the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.

import java.util.Scanner

object Contest06YetAnotherStringScala {
  def playWord(word: String): String = {
    word.foldLeft((true,List[Char]()))((acc,a) => {
      (!acc._1,
        (if (acc._1) {// find next char
          if (a == 'a') 'b' else 'a'
        } else {
          if (a == 'z') 'y' else 'z'
        }) :: acc._2
      )
    })._2.mkString.reverse
  }

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val totalCases = scanner.nextInt
    for (i <- 0 to totalCases) {
      val word = scanner.nextLine()
      System.out.println(playWord(word))
    }
    scanner.close()
  }
}

import java.util.Scanner

object Contest06YetAnotherStringScala {
  def playWord(word: String): String = {
    word.foldLeft((true,List[Char]()))((acc,a) => {
      (!acc._1,
        (if (acc._1) {// find next char
          if (a == 'a') 'b' else 'a'
        } else {
          if (a == 'z') 'y' else 'z'
        }) :: acc._2
      )
    })._2.mkString.reverse
  }

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val totalCases = scanner.nextInt
    for (i <- 0 until totalCases) {
      val word = scanner.nextLine()
      System.out.println(playWord(word))
    }
    scanner.close()
  }
}


Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .

For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.

NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.

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

object Main extends App {

  private val getCount: Array[Int] => Int =
    arr => {
      if (arr.product == 0) {
        val count = arr count (_ == 0)
        if (arr.sum + count == 0) count + 1 else count
      } else if (arr.sum == 0)
        1
      else
        0
    }

  var n = StdIn.readInt()
  var result: ListBuffer[Int] = new ListBuffer

  while (n != 0) {
    StdIn.readLine()
    val line = StdIn.readLine()
    val arr = line split "\\s" map (_.toInt)
    result += getCount(arr)

    n = n - 1
  }

  result foreach println

}

import java.io.PrintWriter
import util.control.Breaks._

object SolutionA {
    val reader = scala.io.StdIn
    def readInt = reader.readLine().toInt
    def readArrayInt = reader.readLine().split(" ").map(_.toInt)

    def multiTest(f: () => Unit): Unit = {
        var t = readInt
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        val n = readInt
        val a = readArrayInt

        var rs = 0
        var sum = 0
        for (i <- 0 until n) {
            if (a(i) == 0) {
                a(i) = 1
                rs += 1

            }
            sum += a(i)
        }

        if (sum == 0)
            rs += 1

        println(rs)
    }

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


The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 × 2 square, such that from the four letters of this square you can make word "face". You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.

The first line contains two space-separated integers, n and m (1 ≤ n, m ≤ 50) — the height and the width of the image, respectively. Next n lines define the image. Each line contains m lowercase Latin letters.

In the single line print the number of faces on the image.

NoteIn the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column:   In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.In the third sample two faces are shown:   In the fourth sample the image has no faces on it.

object First extends App{
  /* Created by bfattahov on 06.06.15. */

  val input = io.Source.stdin.getLines().toSeq
  val photo = input.drop(1)

  val firstLine = Seq.apply(input.head.split(' '): _*).map(_.trim).filterNot(_.isEmpty).take(2).map(_.toInt)
  val rows = firstLine(0)
  val cols = firstLine(1)

  //input.foreach(println)

  if (rows < 2 || cols < 2) {
    println(0)
  } else {
    val faces = (0 to cols - 2).foldLeft(0) { (res, c) => ; res + (0 to rows - 2).count(r => isItFace(c, r))}

    println(faces)
  }

  def isItFace(c: Int, r: Int): Boolean = {
    Seq(
      photo(r).charAt(c),
      photo(r).charAt(c + 1),
      photo(r + 1).charAt(c),
      photo(r + 1).charAt(c + 1)
    ).foldLeft(0) {
      (res, curr) => {
        res + (curr match {
          case 'a' => 1
          case 'e' => 2
          case 'c' => 4
          case 'f' => 8
          case _ => 0
        })
      }
    } == 15
  }
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter

object CF549A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

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

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

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

  def main(args: Array[String]): Unit = {
    val in = new InputReader(System.in)
    val m = in.nextInt()
    val n = in.nextInt()
    val board = Array.fill(m) { in.next()}
    var sum = 0;
    for(i <- 0 until m)
      for( j <- 0 until n) {
        sum += countFace(i,j,board)
      }
    print(sum)
  }

  def countFace(i: Int, j: Int, board: Array[String]): Int = {
    val b = new StringBuilder()
    for(ki <- 0 to 1)
      for(kj <-0 to 1)
        if ( i + ki < board.length && j+ kj < board(0).length )
      {
        b.append(board(i+ki).charAt(j+kj))
      }
    val s = b.toString()
    val face ="face"
    for(i <- 0 until face.length) {
      if ( s.indexOf(face.charAt(i)) == -1) return 0
    }
    return 1
  }
}

import java.util.StringTokenizer

object _549A extends App {
  var token = new StringTokenizer("")

  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val m = next.toInt
  val a = (1 to n).map(i => next).toArray

  val ans = for {
    i <- 0 until n - 1
    j <- 0 until m - 1
    if Set(a(i)(j), a(i)(j + 1), a(i + 1)(j), a(i + 1)(j + 1)) == Set('f', 'a', 'c', 'e')
  } yield 1

  println(ans.sum)
}

object A549 {

  import IO._

  def main(args: Array[String]): Unit = {
    val face = "acef"
    val Array(n, m) = readInts(2)
    val in = Array.fill(n)(read.toCharArray)
    var res = 0
    for(i <- 0 until n-1; j <- 0 until m-1) {
      var str = ""
      str += in(i)(j)
      if(i+1 < n) str += in(i+1)(j)
      if(j+1 < m) str += in(i)(j+1)
      if(i+1 < n && j +1 < m) str += in(i+1)(j+1)

      if(str.sorted.equalsIgnoreCase(face))
        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 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, m) = readInts(2)
  val ss = Array.fill(n){ readLine }

  def check(i: Int, j: Int) = {
    val set = Set(ss(i)(j), ss(i + 1)(j), ss(i)(j + 1), ss(i + 1)(j + 1))
    set('f') && set('a') && set('c') && set('e')
  }

  var res = 0
  for (i <- 0 until n - 1)
    for (j <- 0 until m - 1) {
      if (check(i, j)) res += 1
    }
  println(res)
}

import java.util.Scanner

object A {

	def detectFace(c1:Char, c2:Char, c3:Char, c4:Char):Boolean =
		List(c1, c2, c3, c4).sorted.mkString.equals("acef")

	def countFaces(s1:String, s2:String):Int = {
		return (0 until s1.length() - 1)
			.map(i => detectFace(s1.charAt(i), s1.charAt(i + 1), s2.charAt(i), s2.charAt(i + 1)))
			.map(b => if (b) 1 else 0)
			.reduceLeft(_+_)
	}

	def readAndCountFaces(n:Int):Int = {
		var count:Int = 0
		var s1:String = in.nextLine
		for (i <- 2 to n) {
			var s2:String = in.nextLine
			count += countFaces(s1, s2)
			s1 = s2
		}
		count
	}

	val in:Scanner = new Scanner(System.in)

	def main(args: Array[String]) = {
		var n:Int = in.nextInt
		var m:Int = in.nextInt
		in.nextLine

		val count:Int = if (n > 1 && m > 1) readAndCountFaces(n) else 0

		println(count)
	}

}

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

import scala.collection.mutable

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)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???
    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val a = new Array[Array[Char]](n)
    for (i <- 0 until n) {
      a(i) = next.toCharArray
    }
    var ans = 0
    val b = Array('f', 'a', 'c', 'e')
    for (i <- 0 until n - 1) {
      for (j <- 0 until m - 1) {
        val s = new mutable.HashSet[Char]()
        var flag = true
        s.add(a(i)(j))
        s.add(a(i + 1)(j))
        s.add(a(i + 1)(j + 1))
        s.add(a(i)(j + 1))
        b.foreach(x => {
          if (!s.contains(x)) {
            flag = false
          }
        })
        if (flag)
          ans += 1

      }
    }
    out.println(ans)
    return 0
  }
}

import scala.collection.immutable.IndexedSeq
import scala.collection.mutable

object A {

  def check(a: IndexedSeq[String], i: Int, j: Int): Boolean = {
    val s=mutable.TreeSet[Char]()
    s+=a(i).charAt(j)
    s+=a(i).charAt(j+1)
    s+=a(i+1).charAt(j)
    s+=a(i+1).charAt(j+1)
    s.mkString("") == "acef"
  }

  def main(args: Array[String]) {
    val Array(n,m)=io.StdIn.readLine().split(" ").map(_.toInt)
    val a = for (i<-1 to n) yield io.StdIn.readLine()
    var k=0
    for (i<-0 until n-1)
      for (j<-0 until m-1){
        if (check(a,i,j))
          k+=1
      }
    println(k)
  }
}


You are given a binary string $$$s$$$ (recall that a string is binary if each character is either $$$0$$$ or $$$1$$$).Let $$$f(t)$$$ be the decimal representation of integer $$$t$$$ written in binary form (possibly with leading zeroes). For example $$$f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$$$ and $$$f(000100) = 4$$$.The substring $$$s_{l}, s_{l+1}, \dots , s_{r}$$$ is good if $$$r - l + 1 = f(s_l \dots s_r)$$$.For example string $$$s = 1011$$$ has $$$5$$$ good substrings: $$$s_1 \dots s_1 = 1$$$, $$$s_3 \dots s_3 = 1$$$, $$$s_4 \dots s_4 = 1$$$, $$$s_1 \dots s_2 = 10$$$ and $$$s_2 \dots s_4 = 011$$$. Your task is to calculate the number of good substrings of string $$$s$$$.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. The only line of each query contains string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), consisting of only digits $$$0$$$ and $$$1$$$. It is guaranteed that $$$\sum\limits_{i=1}^{t} |s_i| \le 2 \cdot 10^5$$$.

For each query print one integer — the number of good substrings of string $$$s$$$.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val S = ns()
      val N = S.length
      val cnt1 = S.count(_ == '1')
      var cnt2 = 0
      REP(N - 1) { i =>
        if (S(i) == '1' && S(i + 1) == '0') cnt2 += 1
      }

      var cnt3 = 0L
      var c = 0 // 連続した0の個数
      REP(N) { i =>
        if (S(i) == '0') c += 1
        else {
          var x = 0
          REP(min(20, N - i)) { j =>
            if (S(i + j) == '1') x += 1
            if (x > 2 && x <= c + j + 1) cnt3 += 1
            x *= 2
          }
          c = 0
        }
      }

      debug(s"$cnt1 $cnt2 $cnt3")

      val ans = cnt1 + cnt2 + cnt3
      out.println(ans)
    }
  }
}

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(t) = readInts(1)

  for (_ <- 1 to t) {
    val s = readLine.map(_ - '0')
    var res = 0L

    val prevZeros = Array.fill(s.length)(0)
    var z = 0
    for (i <- s.indices) {
      if (s(i) == 0) {
        z += 1
      } else z = 0
      prevZeros(i) = z
    }

    for (r <- s.indices) {
      var len = 0
      var x = 0L
      while (1L << len <= r + 1 && len <= r) {
        x = x + (s(r - len) << len)
        len += 1
        if (x == len) res += 1
        //println(len, x, r)
      }
      //if (len <= r) println("!", len, x, prevZeros(r - len))
      if (len <= r && prevZeros(r - len) + len >= x && x > len) res += 1
    }

    println(res)
  }
}


A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you:  choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively),  swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously?

The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones.

Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case.

NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 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
  }
}

object Workspace {
  import Main._
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n = ni()
      var zeros, ones = 0
      var odds = 0
      var bitOdds = 0
      REP(n) { _ =>
        val s = ns()
        val z = s.count(_ == '0')
        val o = s.length - z
        zeros += z
        ones += o
        if (s.length % 2 == 1) odds += 1
      }

      debug(s"$zeros $ones $odds")

      if (zeros % 2 == 1) bitOdds += 1
      if (ones % 2 == 1) bitOdds += 1

      val ok = if (bitOdds == 0) {
        odds % 2 == 0
      } else if (bitOdds == 1) {
        odds % 2 == 1
      } else {
        odds >= 2 && odds % 2 == 0
      }

      if (ok) {
        out.println(n)
      } else {
        out.println(n - 1)
      }
    }
  }
}

object BinaryPalindrome extends App {

  val array = readFromTerminal()
  for (row <- array)
    println(compute(row))

  def readFromTerminal(): Seq[Seq[String]] = {
    val q = readInt()
//    val q = 4
//    val list = List(
//      List("0"),
//      List("1110","100110","010101"),
//      List("11111","000001"),
//      List("001","11100111"),
//    )
//1
//2
//2
//2
    val list: Seq[Seq[String]] = (1 to q).toList.map { j => {
      val n = readInt()
      val t: Seq[String] = for (i <- 1 to n) yield readLine()
      t
    }}
    list
  }

  def compute(rows: Seq[String]): Int = {
    val (zeros, ones): (Int, Int) = rows.map{ row => (
      row.count{ c => c == '0'},
      row.count{ c => c =='1'}
    )}.fold((0,0))((acc, pair) => (acc._1 + pair._1,acc._2 + pair._2))
    //все длины
    val lengths = rows.map{row => row.length }
    //сколько есть пар
    val possiblePairs = (zeros / 2)  + (ones / 2)
    // сколько нужно пар
    val needPairs = lengths.fold(0){(acc, length) => acc + length/2}

    val unpairedNumbers = lengths.sum - possiblePairs*2
    if ((possiblePairs - needPairs) <0 )
      lengths.size+(possiblePairs - needPairs)
    else
      lengths.size
  }
}