While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1, a2, ..., am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1, f2, ..., fn of length n and for each number ai got number bi = fai. To finish the prank he erased the initial sequence ai.It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the lengths of sequences fi and bi respectively. The second line contains n integers, determining sequence f1, f2, ..., fn (1 ≤ fi ≤ n). The last line contains m integers, determining sequence b1, b2, ..., bm (1 ≤ bi ≤ n).

Print "Possible" if there is exactly one sequence ai, such that bi = fai for all i from 1 to m. Then print m integers a1, a2, ..., am. If there are multiple suitable sequences ai, print "Ambiguity". If Spongebob has made a mistake in his calculations and no suitable sequence ai exists, print "Impossible".

NoteIn the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.In the third sample fi ≠ 3 for all i, so no sequence ai transforms into such bi and we can say for sure that Spongebob has made a mistake.

//package scala_tutorial

import scala.collection.mutable._
object source {
	def main(args : Array[String]) {
		val Array(n, m) = readLine split " " map (_.toInt)
		var f = readLine split " " map (_.toInt)
		var b = readLine split " " map (_.toInt)

		val cnt = new HashMap[Int, Int]().withDefaultValue(0)
		val pos = new HashMap[Int, Int]().withDefaultValue(-1)

		var index = 0
		for(index <- 0 until n)
		{
			cnt(f(index))+=1
			pos(f(index))=index+1
		}
		var ambiguity = false
		for(index <- 0 until m)
		{
			if(cnt(b(index))==0)
			{
				println("Impossible")
				System.exit(0)
			}
			else if(cnt(b(index))>1)
			{
				ambiguity = true
			}
		}
		if(ambiguity)
		{
			println("Ambiguity")
		}
		else
		{
			println("Possible")
			println(b map (elem => pos(elem)) mkString " ")
		}
	}
}

//package scala_tutorial

import scala.collection.mutable._
object source {
	def main(args : Array[String]) {
		val Array(n, m) = readLine split " " map (_.toInt)
		var f = readLine split " " map (_.toInt)
		var b = readLine split " " map (_.toInt)
		var index = 0
		var imap = new HashMap[Int, Int]
		var cnt = new HashMap[Int, Int]().withDefaultValue(0)
		var ret = 0
		var ans = Array.ofDim[Int](m+1)
		for (index <- 0 until n)
		{
			cnt(f(index))+=1
			imap(f(index))=index+1
		}
		for (index <- 0 until m)
		{
			if(imap.contains(b(index))==false)
			{
				println("Impossible")
				System.exit(0)
			}
			else
			{
				if(cnt(b(index))>1)
				{
					ret = 1
				}
				else
				{
					ans(index)=imap(b(index))
				}
			}
		}
		if(ret == 1)println("Ambiguity")
		else
		{
			println("Possible")
			for (index <- 0 until m)
			{
				printf("%d ", ans(index))
			}
		}

	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val f = in.next().split(' ').map(_.toInt)
  val b = in.next().split(' ').map(_.toInt)
  val map = f.indices.foldLeft(Map.empty[Int, Set[Int]]) {
    case (m, i) =>
      val value = f(i)
      if (m.contains(value))
        m + (value -> (m(value) + (i + 1)))
      else
        m + (value -> Set(i + 1))
  }

  val res = b.foldLeft((0, List.empty[Int])) {
    case ((2, _), _) => (2, Nil)
    case (_, el) if !map.contains(el) => (2, Nil)
    case ((1, _), el) => (1, Nil)
    case (_, el) if map(el).size > 1 => (1, Nil)
    case ((0, list), el) => (0, map(el).head :: list)
  }
  if (res._1 == 0) {
    println("Possible")
    println(res._2.reverse.mkString(" "))
  }
  else if (res._1 == 1)
    println("Ambiguity")
  else
    println("Impossible")
}

import scala.collection._

object B 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 fs = readInts(n)
  val bs = readInts(m)

  val fCnts = Array.fill(n + 1){ 0 }
  for (f <- fs) fCnts(f) += 1

  for (b <- bs) if (fCnts(b) == 0) {
    println("Impossible")
    System.exit(0)
  }

  for (b <- bs) if (fCnts(b) > 1) {
    println("Ambiguity")
    System.exit(0)
  }

  val bToA = fs.zipWithIndex.toMap.mapValues(_ + 1)
  val as = bs.map(bToA)

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

  println("Possible")
  println(as.mkString(" "))

  Console.flush
}

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

object _599B extends CodeForcesApp {
  override type Result = String

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, m) = (nextInt(), nextInt())
    val f = Seq.tabulate(n)(i => nextInt() -> (i+1)).toMultiMap
    val b = Seq.fill(m)(nextInt())

    var result: Option[String] = None

    val ans = b map {i =>
      f get i match {
        case None | Some(Nil) =>
          result = Some("Impossible")
          0
        case Some(_ :: _ :: _) =>
          if (!(result contains "Impossible")) result = Some("Ambiguity")
          0
        case Some(x :: Nil) =>
          x
      }
    }

    result getOrElse ans.mkString("Possible\n", " ", "")
  }

  implicit class PairsExtensions[A, B](t: Traversable[(A, B)]) {
    def toMultiMap: Map[A, List[B]] = t.groupBy(_._1).mapValues(_.map(_._2).toList)
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

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

object _599B extends CodeForcesApp {
  override type Result = String

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, m) = (nextInt(), nextInt())
    val f = Seq.tabulate(n)(i => nextInt() -> (i+1)).toMultiMap withDefaultValue Nil
    val b = Seq.fill(m)(nextInt())

    var result: Option[String] = None

    val ans = b map f map {
      case Nil => result = Some("Impossible"); 0
      case x :: Nil =>  x
      case _ =>
        if (!(result contains "Impossible")) result = Some("Ambiguity")
        0
    }

    result getOrElse ans.mkString("Possible\n", " ", "")
  }

  implicit class PairsExtensions[A, B](t: Traversable[(A, B)]) {
    def toMultiMap: Map[A, List[B]] = t.groupBy(_._1).mapValues(_.map(_._2).toList)
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val F = readLine().split(" ").map(_.toInt)
  val B = readLine().split(" ").map(_.toInt)

  val Bcounter = Array.ofDim[Int](n + 1)
  val Fcounter = Array.ofDim[Int](n + 1)

  B.foreach(x => Bcounter(x) += 1)
  F.foreach(x => Fcounter(x) += 1)

  if (B.exists(x => Fcounter(x) == 0)) {
    println("Impossible")
  } else if (B.exists(x => Fcounter(x) > 1)) {
    println("Ambiguity")
  } else {
    println("Possible")
    val M = F.zipWithIndex.map {
      x => (x._1, x._2 + 1)
    }.toMap

    println(B.map(x => M(x)).mkString(" "))
  }

}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val ft=Array.fill(n+1)(-1)
    for(i<-0 until n){
      val t=nextInt
      if(ft(t)== -1){
        ft(t)=i+1
      }else{
        ft(t)= -2
      }
    }
    var flag=0
    val a=Array.ofDim[Int](m)
    breakable{
      for(i<-0 until m){
        val b=nextInt
        if(ft(b)== -1){
          flag=2
          break
        }else if(ft(b)== -2&& flag!=2){
          flag=1

        }else{
          a(i)=ft(b)
        }
      }
    }
    if(flag==2){
      out.println("Impossible")
    }else if(flag==1){
      out.println("Ambiguity")

    }else{
      out.println("Possible")
      for(i<-0 until m-1){
        out.print(a(i)+" ")
      }
      out.println(a(m-1))
    }
    //code ends here
    out.flush
    out.close
  }
}

//package scala_tutorial

import scala.collection.mutable._
object source {
	def main(args : Array[String]) {
		val Array(n, m) = readLine split " " map (_.toInt)
		var f = readLine split " " map (_.toInt)
		var b = readLine split " " map (_.toInt)
		var index = 0
		var imap = new HashMap[Int, Int]
		var cnt = new HashMap[Int, Int]().withDefaultValue(0)
		var ret = 0
		var ans = Array.ofDim[Int](m+1)
		for (index <- 0 until n)
		{
			cnt(f(index))+=1
			imap(f(index))=index+1
		}
		for (index <- 0 until m)
		{
			if(imap.contains(b(index))==false)
			{
				ret = 2
			}
			else
			{
				if(cnt(b(index))>1)
				{
					ret = 1
				}
				else
				{
					ans(index)=imap(b(index))
				}
			}
		}
		if(ret == 1)println("Ambiguity")
		else if(ret == 2)println("Impossible")
		else
		{
			println("Possible")
			for (index <- 0 until m)
			{
				printf("%d ", ans(index))
			}
		}

	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data1 = in.next().split(' ').map(_.toInt).sorted
  val data2 = in.next().split(' ').map(_.toInt).sorted
  val impossible = n != m
  val duplicates = (data1.distinct.length != data1.length) || (data2.distinct.length != data2.length)
  val res = data1.zip(data2).foldLeft(if (impossible) 2 else if (duplicates) 1 else 0) {
    case (2, _) => 2
    case (_, (el1, el2)) if el1 != el2 => 2
    case (status, _) => status
  }
  if (res == 0) {
    println("Possible")
    println(data1.mkString(" "))
  }
  else if (res == 1)
    println("Ambiguity")
  else
    println("Impossible")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data1unsorted = in.next().split(' ').map(_.toInt)
  val data1 = data1unsorted.sorted
  val data2 = in.next().split(' ').map(_.toInt).sorted
  val impossible = n != m
  val duplicates = (data1.distinct.length != data1.length) || (data2.distinct.length != data2.length)
  val res = data1.zip(data2).foldLeft(if (impossible) 2 else if (duplicates) 1 else 0) {
    case (2, _) => 2
    case (_, (el1, el2)) if el1 != el2 => 2
    case (status, _) => status
  }
  if (res == 0) {
    println("Possible")
    println(data1unsorted.mkString(" "))
  }
  else if (res == 1)
    println("Ambiguity")
  else
    println("Impossible")
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val F = readLine().split(" ").map(_.toInt)
  val B = readLine().split(" ").map(_.toInt)

  val Bcounter = Array.ofDim[Int](n + 1)
  val Fcounter = Array.ofDim[Int](n + 1)

  B.foreach(x => Bcounter(x) += 1)
  F.foreach(x => Fcounter(x) += 1)

  if (F.exists(x => Bcounter(x) == 0)) {
    println("Impossible")
  } else if (B.exists(x => Fcounter(x) > 1)) {
    println("Ambiguity")
  } else {
    println("Possible")
    val M = F.zipWithIndex.map {
      x => (x._1, x._2 + 1)
    }.toMap

    println(B.map(M(_)).mkString(" "))
  }

}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val F = readLine().split(" ").map(_.toInt)
  val B = readLine().split(" ").map(_.toInt)

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

  B.foreach(x => Bcounter(x) += 1)

  if (F.exists(x => Bcounter(x) == 0)) {
    println("Impossible")
  } else if (F.forall(x => Bcounter(x) == 1)) {
    println("Possible")
  } else {
    println("Ambiguity")
  }

}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val f=(for(i<-0 until n) yield (nextInt,i+1)) sorted
    val a=Array.ofDim[Int](m)
    var flag=0
    breakable{
      for(i<-0 until m){
        val b=nextInt
        var l=0
        var r=n-1
        while(l<r-1){
          val c=(l+r)/2
          if(f(c)._1>b){
            r=c
          }else{
            l=c
          }
        }
        var ma= -1
        if(f(l)._1==b){
          ma=l
        }else if(f(r)._1==b){
          ma=r
        }else{
          flag=2
          break

        }
        if(ma>0 && f(ma-1)._1==b){
          flag=1
          break
        }
        if(ma<n-1 && f(ma+1)._1==b){
          flag=1
          break
        }
        a(i)=f(ma)._2
      }
    }
    if(flag==2){
      out.println("Impossible")
    }else if(flag==1){
      out.println("Ambiguity")

    }else{
      out.println("Possible")
      for(i<-0 until m){
        out.print(a(i)+" ")
      }
    }
    //code ends here
    out.flush
    out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val ft=Array.fill(n+1)(-1)
    for(i<-0 until n){
      val t=nextInt
      if(ft(t)== -1){
        ft(t)=i+1
      }else{
        ft(t)= -2
      }
    }
    var flag=0
    val a=Array.ofDim[Int](m)
    breakable{
      for(i<-0 until m){
        val b=nextInt
        if(ft(b)== -1){
          flag=2
          break
        }else if(ft(b)== -2){
          flag=1
          break
        }else{
          a(i)=ft(b)
        }
      }
    }
    if(flag==2){
      out.println("Impossible")
    }else if(flag==1){
      out.println("Ambiguity")

    }else{
      out.println("Possible")
      for(i<-0 until m-1){
        out.print(a(i)+" ")
      }
      out.println(a(m-1))
    }
    //code ends here
    out.flush
    out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val ft=Array.fill(n+1)(-1)
    for(i<-0 until n){
      val t=nextInt
      if(ft(t)== -1){
        ft(t)=i+1
      }else{
        ft(t)= -2
      }
    }
    var flag=0
    val a=Array.ofDim[Int](m)
    breakable{
      for(i<-0 until m){
        val b=nextInt
        if(ft(b)== -1){
          flag=2
          break
        }else if(ft(b)== -2){
          flag=1
          break
        }else{
          a(i)=ft(b)
        }
      }
    }
    if(flag==2){
      out.println("Impossible")
    }else if(flag==1){
      out.println("Ambiguity")

    }else{
      out.println("Possible")
      for(i<-0 until m){
        out.print(a(i)+" ")
      }
    }
    //code ends here
    out.flush
    out.close
  }
}


One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?He needs your help to check it.A Minesweeper field is a rectangle $$$n \times m$$$, where each cell is either empty, or contains a digit from $$$1$$$ to $$$8$$$, or a bomb. The field is valid if for each cell:   if there is a digit $$$k$$$ in the cell, then exactly $$$k$$$ neighboring cells have bombs.  if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $$$8$$$ neighboring cells).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the sizes of the field. The next $$$n$$$ lines contain the description of the field. Each line contains $$$m$$$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $$$1$$$ to $$$8$$$, inclusive.

Print "YES", if the field is valid and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrarily.

NoteIn the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.You can read more about Minesweeper in Wikipedia's article.

import scala.io.StdIn

object Minesweeper extends App {

  type Field = Array[Array[String]]

  val l1s = StdIn.readLine().split(" ")
  val n = l1s(0).toInt
  val m = l1s(1).toInt

  val field = new Field(n)
  for (i <- 0 until n) {
    field(i) = StdIn.readLine().split("")
  }

  impl(n, m, field) match {
    case true => print("YES")
    case false => print("NO")
  }

  def impl(n: Int, m: Int, field: Field): Boolean = {
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (!validateNeighbors(i, j, field, n, m)) return false
      }
    }
    true
  }

  private
  def validateNeighbors(i: Int, j: Int, field: Field, n: Int, m: Int): Boolean = {
    if (field(i)(j) != "*") {
      val mines =
        getMine(-1, -1, i, j, n, m, field) +
          getMine(-1, 0, i, j, n, m, field) +
          getMine(-1, 1, i, j, n, m, field) +
          getMine(0, -1, i, j, n, m, field) +
          getMine(0, 1, i, j, n, m, field) +
          getMine(1, -1, i, j, n, m, field) +
          getMine(1, 0, i, j, n, m, field) +
          getMine(1, 1, i, j, n, m, field)

      if (field(i)(j) == ".") {
        if (mines == 0) true
        else false
      } else {
        if (mines == field(i)(j).toInt) true
        else false
      }
    } else {
      true
    }
  }

  private
  def getMine(i_offset: Int, j_offset: Int, i: Int, j: Int, n: Int, m: Int, field: Field): Int = {
    if (inField(i + i_offset, j + j_offset, n, m)) {
      if (field(i + i_offset)(j + j_offset) == "*") 1
      else 0
    } else 0
  }

  private
  def inField(i: Int, j: Int, n: Int, m: Int): Boolean = {
    if (i < 0 || i >= n) false
    else if (j < 0 || j >= m) false
    else true
  }
}

object _984B extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val n, _ = io.read[Int]
    val map: Vector[String] = io.read(n)

    def bombCount(i: Int, j: Int) = {
      var c = 0
      for {
        dx <- -1 to 1
        row <- map.lift(i + dx)
        dy <- -1 to 1
        if !(dx == 0 && dy == 0)
        col <- row.lift(j + dy)
        if col == '*'
      } c += 1
      c
    }

    var ok = true
    for {
      i <- map.indices
      j <- map(i).indices
      if map(i)(j) != '*'
      c = if (map(i)(j).isDigit) map(i)(j) - '0' else 0
    } ok &= (c == bombCount(i, j))

    io.write(if (ok) "YES" else "NO")
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.Look at the input part of the statement, s is given in a special form.

In the first line you're given a string a (1 ≤ |a| ≤ 105), containing digits only. In the second line you're given an integer k (1 ≤ k ≤ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.

Print a single integer — the required number of ways modulo 1000000007 (109 + 7).

NoteIn the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.

object C extends App {

  def readString = Console.readLine

  val as = readString //Array.fill(100000)('5')
  val k = readString.toLong

  var x = BigInt(0)
  val TWO = BigInt(2)
  val M = BigInt(1000000007)
  val l = as.length()

  val a = TWO.modPow(k * l, M) - 1
  val b = TWO.modPow(l, M) - 1
  val y = a * b.modInverse(M)

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
    x %= M
  }

  println(x * y % M)
}

object C extends App {

  def readString = Console.readLine
  val as = readString
  val k = readString.toLong

  var x = 0
  val TWO = BigInt(2)
  val M = 1000000007
  val l = as.length()

  val a = TWO.modPow(k * l, M) - 1
  val b = TWO.modPow(l, M) - 1
  val y = a * b.modInverse(M)

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
    x %= M
  }

  println(x * y % M)
}

object CF327C extends App {
  val s = Console.readLine
  val n : Long = s.size.toLong
  val k : Long = Console.readLine.toLong
  val md = 1000000007L

  def p2(y : Long, x : Long) : Long = {
    if (x == 0) 1 else {
      val t = p2(y, x/2)
      if (x % 2 == 0) (t * t) % md else (((y * t) % md) * t) % md
    }
  }

  def inv(x : Long) : Long = {
    p2(x, md - 2)
  }

  val res = (0 until n.toInt).map{
    x => if (s(x) == '0' || s(x) == '5') p2(2, x) else 0
  }.reduce((x, y) => (x + y) % md)

  val outer = (p2(2, k * n) - 1 + md) % md * inv((p2(2, n) - 1 + md)% md) % md

  println (res * outer % md)
}

object C extends App {

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

  val as = readString //Array.fill(100000)('5') //
  val k = readString.toInt

  var x = BigInt(0)
  val TWO = BigInt(2)
  val M = BigInt(1000000007)
  val l = as.length()

  val a = k min l
  val b = k max l

  val y = ((TWO.modPow(b, M).modPow(a, l * M) - 1 + M) % M) / ((TWO.pow(l)- 1))

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
  }

  println(x * y % M)
}

object C extends App {

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

  val as = readString //Array.fill(100000)('5')
  val k = readString.toInt

  var x = 0L
  val TWO = BigInt(2)
  val M = 1000000007L
  val l = as.length()

  val a = TWO.modPow(k * l, M) - 1
  val b = TWO.modPow(l, M) - 1
  val y = a * b.modInverse(M)

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
    x %= M
  }

  println(x * y % M)
}

object C extends App {

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

  val as = Array.fill(100000)('5')
  val k = readString.toInt

  var x = 0L
  val TWO = BigInt(2)
  val M = 1000000007
  val l = as.length()

  val a = TWO.modPow(k * l, M) - 1
  val b = TWO.modPow(l, M) - 1
  val y = a * b.modInverse(M)

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
    x %= M
  }

  println(x * y % M)
}

object C extends App {

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

  val as = readString //Array.fill(100000)('5') //
  val k = readString.toInt

  var x = BigInt(0)
  val TWO = BigInt(2)
  val M = BigInt(1000000007)
  val l = as.length()

  val a = k min l
  val b = k max l

  val y = ((TWO.modPow(b, M).modPow(a, l * M) - 1 + M) % M) / ((TWO.modPow(l, M) + M - 1) % M)

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
  }

  println(x * y % M)
}

object C extends App {

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

  val as = readString //Array.fill(100000)('5') //
  val k = readString.toInt

  var x = BigInt(0)
  val TWO = BigInt(2)
  val M = BigInt(1000000007)
  val l = as.length()

  val a = k min l
  val b = k max l

  val y = (TWO.modPow(b, M).modPow(a, l * M) - 1) / ((TWO.pow(l)- 1))

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
  }

  println(x * y % M)
}

object C extends App {

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

  val as = readString //Array.fill(100000)('5') //
  val k = readString.toInt

  var x = BigInt(0)
  val TWO = BigInt(2)
  val M = BigInt(1000000007)
  val l = as.length()

  val a = k min l
  val b = k max l

  val y = (TWO.modPow(b, M).modPow(a, l * M) - 1) / (TWO.modPow(l, M) - 1)

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
  }

  println(x * y % M)
}

object C extends App {

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

  val as = readString //Array.fill(100000)('5') //
  val k = readString.toInt

  var x = BigInt(0)
  val TWO = BigInt(2)
  val M = BigInt(1000000007)
  val l = as.length()

  val y = (TWO.modPow(k * l, l * M) - 1) / (TWO.modPow(l, M) - 1)

  for (c <- as.reverse) {
    x = 2 * x
    if (c == '0' || c == '5') x += 1
  }

  println(x * y % M)
}

object CF327C extends App {
  val s = Console.readLine
  val n = s.size
  val k = Console.readLine.toInt
  val md = 1000000007

  def p2(y : Long, x : Long) : Long = {
    if (x == 0) 1 else {
      val t = p2(y, x/2)
      if (x % 2 == 0) (t * t) % md else ((y * t) % md) * t % md
    }
  }

  def inv(x : Long) : Long = {
    p2(x, md - 2)
  }

  val res = ((0 until n).reverse.map{
    x => {
      if (s(x) == '0' || s(x) == '5') p2(2, x) else 0
    }
  }.reduce((x, y) => (x + y) % md) * ((p2(2, k * n) - 1 + md) % md))% md * inv((p2(2, n) - 1 + md)% md) % md

  println (res)
}

object CF327C extends App {
  val s = Console.readLine
  val n = s.size
  val k = Console.readLine.toInt
  val md = 1000000007L

  def p2(y : Long, x : Long) : Long = {
    if (x == 0) 1 else {
      val t = p2(y, x/2)
      if (x % 2 == 0) (t * t) % md else (((y * t) % md) * t) % md
    }
  }

  def inv(x : Long) : Long = {
    p2(x, md - 2)
  }

  val res = (((0 until n).reverse.map{
    x => {
      if (s(x) == '0' || s(x) == '5') p2(2, x) else 0
    }
  }.reduce((x, y) => (x + y) % md) * ((p2(2, k * n) - 1 + md) % md))% md * inv((p2(2, n) - 1 + md)% md)) % md

  println (res)
}

object CF327C extends App {
  val s = Console.readLine
  val n = s.size
  val k = Console.readLine.toInt
  val md = 1000000007

  def p2(y : Long, x : Long) : Long = {
    if (x == 0) 1 else {
      val t = p2(y, x/2)
      if (x % 2 == 0) (t * t) % md else ((y * t) % md) * t % md
    }
  }

  def inv(x : Long) : Long = {
    p2(x, md - 2)
  }

  val res = ((0 until n).reverse.map{
    x => {
      if (s(x) == '0' || s(x) == '5') p2(2, x) else 0
    }
  }.reduce((x, y) => (x + y) % md) * ((p2(2, k * n) - 1 + md) % md))% md * inv(p2(2, n) - 1) % md

  println (res)
}

object CF327C extends App {
  val s = Console.readLine
  val n = s.size
  val k = Console.readLine.toInt
  val md = 1000000007

  def p2(y : Long, x : Long) : Long = {
    if (x == 0) 1 else {
      val t = p2(y, x/2)
      if (x % 2 == 0) (t * t) % md else (((y * t) % md) * t) % md
    }
  }

  def inv(x : Long) : Long = {
    p2(x, md - 2)
  }

  val res = (((0 until n).reverse.map{
    x => {
      if (s(x) == '0' || s(x) == '5') p2(2, x) else 0
    }
  }.reduce((x, y) => (x + y) % md) * ((p2(2, k * n) - 1 + md) % md))% md * inv((p2(2, n) - 1 + md)% md)) % md

  println (res)
}


Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.

Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.

NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val map: Map[String, Int] = Map(
      "XXXS" -> 0,
      "XXS" -> 1,
      "XS" -> 2,
      "S" -> 3,
      "M" -> 4,
      "L" -> 5,
      "XL" -> 6,
      "XXL" -> 7,
      "XXXL" -> 8)

    val readArr = readStd(n, map, _: Array[Int], _: Int)
    val add = readArr(_: Array[Int], 1)
    val minus = readArr(_: Array[Int], -1)

    val arr = (add andThen minus) (Array.fill(9)(0))

    println(arr.filter({x: Int => x < 0}).map({x: Int => -x}).sum)
  }

  def readStd(n: Int, map: Map[String, Int], arr: Array[Int], add: Int): Array[Int] = {
    if (n != 0) {
      arr(map(StdIn.readLine)) += add
      readStd(n - 1, map, arr, add)
    } else {
      arr
    }
  }
}


Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.

The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.  It is guaranteed that the given set of edges specifies a tree.

A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.

NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test:  The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test:  The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _580C extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  val hasCats = IndexedSeq.fill(n)(nextInt == 1)
  val edge = map[Int].to(List.empty[Int])
  repeat(n-1) {
    val (i, j) = (nextInt, nextInt)
    edge(i) = j :: edge(i)
    edge(j) = i :: edge(j)
  }

  val visited = bag[Int]

  def solve(pos: Int, prevCats: Int): Int = {
    visited += pos
    val cats = if (hasCats(pos - 1)) 1 + prevCats else 0
    edge(pos).filterNot(visited) match {
      case _ if cats > m => 0
      case Nil => 1
      case children => children.map(solve(_, cats)).sum
    }
  }

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

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _580C extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  val hasCats = IndexedSeq.fill(n)(nextInt == 1)
  val edge = map[Int].to(Set.empty[Int])
  repeat(n-1) {
    val (i, j) = (nextInt, nextInt)
    edge(i) = edge(i) + j
    edge(j) = edge(j) + i
  }

  val visited = mutable.Set.empty[Int]

  def solve(pos: Int, prevCats: Int): Int = {
    visited += pos
    val cats = if (hasCats(pos - 1)) 1 + prevCats else 0
    if (cats > m) {
      0     // more than m consecutive cats. Exit!
    } else {
      val children = edge(pos).filterNot(visited).view
      if (children.isEmpty) {
        1           // Leaf node
      } else {
        var sum = 0     // inner node
        for {i <- children} {
          sum += solve(i, cats)
        }
        sum
      }
    }
  }

  solve(1, 0)
})
/****************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  final def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

object Solution extends App {
val in = scala.io.Source.stdin.getLines()
val Array(n, m) = in.next().split(" ").map(_.toInt)
val cats = in.next().split(" ").map(_.toInt)
val nodes = Array.fill(n){List.empty[Int]}
(1 until n).foreach { _ =>
val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
nodes(a) ::= b
nodes(b) ::= a
}

def count(i: Int, parent: Int, soFar: Int, found: Boolean): Int = {
val nSoFar = if (cats(i) == 1) soFar + 1 else 0
val nFound = found || nSoFar == m + 1
val children = nodes(i).filter(_ != parent).map{j => count(j, i, nSoFar, nFound)}
if (children.isEmpty)
if (nFound) 0 else 1
else
children.sum
}

println(count(0, 0, 0, false))
}

/**
 * @author netman
 */

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

object HelloWorld {

  class InputReader(reader: BufferedReader) {

    var tokenizer: StringTokenizer = null;

    def this(stream: InputStream) = {
      this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));
    }

    def this(f: File) = {
      this(new BufferedReader(new FileReader(f), (1 << 20)));
    }

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

    def nextInt(): Int = next().toInt

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

    def close() = reader.close();
  }

  class OutputWriter(writer: PrintWriter) {
    def this(stream: OutputStream) {
      this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));
    }

    def this(f: File) = {
      this(new PrintWriter(new BufferedWriter(new FileWriter(f))));
    }

    def print(x: Any) = writer.print(x);

    def println(x: Any) = writer.println(x);

    def close() = writer.close();
  }

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

  var a: Array[Int] = null
  var g: Array[ArrayBuffer[Int]] = null
  var m = 0
  var result = 0

  def dfs(v: Int, p: Int, cur: Int): Unit = {
    val ncur = if (a(v) == 0) 0 else cur + 1
    if (ncur <= m) {
    if (g(v).length == 1 && v != 1) {
      result += 1
      //out.println(v)
    }
    for (to <- g(v)) {
      if (to != p) {
        dfs(to, v, ncur)
      }
    }
    }
  }

  def main(args: Array[String]): Unit = {
    val n = in.nextInt
    m = in.nextInt

    a = new Array[Int](n + 1)
    g = Array.fill[ArrayBuffer[Int]](n + 1)(new ArrayBuffer[Int])

    for (i <- 1 to n) {
      a(i) = in.nextInt
    }

    for (i <- 1 to n - 1) {
      val (x, y) = (in.nextInt, in.nextInt)
      g(x) += y
      g(y) += x
    }

    dfs(1, -1, 0)

    out.println(result)

    out.close
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/580/C
object KefaAndPark {
  case class Cou(var c:Int=0)
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var line=in.readLine()
    val n=line.split(" ")(0).toInt
    val m=line.split(" ")(1).toInt
    val cats=in.readLine().split(" ").map(_.toInt)
    val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for(i<- 0 until n-1){
      line=in.readLine()
      addUndirectedEdge(graph,line.split(" ")(0).toInt-1,(line.split(" ")(1).toInt-1))
    }
    getNumberOfPossibleRestaurants(graph,n,m,cats)
  }

  def getNumberOfPossibleRestaurants(graph:Array[ArrayBuffer[Int]],n:Int,m:Int,cats:Array[Int]):Int={
    val cou=Cou()
    postOrder(graph,cats,0,-1,cats(0),m,cou)
    println(cou.c)
    return cou.c
  }

  def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,pr:Int,curM:Int,m:Int,cou: Cou):Unit={
    if(curM<=m){
      var x=1
      for(i<- 0 until graph(n).length ){
        if(graph(n)(i)!=pr) {
          x=0
          postOrder(graph, cats, graph(n)(i), n, cats(graph(n)(i))*curM+cats(graph(n)(i)), m, cou)
        }
      }
      cou.c+=x
    }
  }
  def addUndirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {
    //It is an undirected graph, so the an edge a to b can be used to travel both a to b and b to aa
    graph(u) += v
    graph(v) += u
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/580/C
object KefaAndPark {
  case class Cou(var c:Int=0)
  var graph:Array[ArrayBuffer[Int]] =null
  var cats:Array[Int]=null
  var m:Int=0
  val cou=Cou()
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var line=in.readLine()
    val n=line.split(" ")(0).toInt
    m=line.split(" ")(1).toInt
    cats=in.readLine().split(" ").map(_.toInt)
    graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for(i<- 0 until n-1){
      line=in.readLine()
      addUndirectedEdge(graph,line.split(" ")(0).toInt-1,(line.split(" ")(1).toInt-1))
    }
    postOrder(0,-1,cats(0))
    println(cou.c)
  }

  def postOrder(n:Int,pr:Int,curM:Int):Unit={
    if(curM<=m){
      var x=1
      for(i<- 0 until graph(n).length ){
        if(graph(n)(i)!=pr) {
          x=0
          postOrder(graph(n)(i), n, cats(graph(n)(i))*curM+cats(graph(n)(i)))
        }
      }
      cou.c+=x
    }
  }
  def addUndirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {
    //It is an undirected graph, so the an edge a to b can be used to travel both a to b and b to aa
    graph(u) += v
    graph(v) += u
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/580/C
object KefaAndPark {
  case class Cou(var c:Int=0)
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var line=in.readLine()
    val n=line.split(" ")(0).toInt
    val m=line.split(" ")(1).toInt
    val cats=in.readLine().split(" ").map(_.toInt)
    val edges=new ArrayBuffer[Int]()
    for(i<- 0 until n-1){
      line=in.readLine()
      edges+=(line.split(" ")(0).toInt-1)
      edges+=(line.split(" ")(1).toInt-1)
    }
    getNumberOfPossibleRestaurants(n,m,cats,edges)
  }

  def getNumberOfPossibleRestaurants(n:Int,m:Int,cats:Array[Int],edges:ArrayBuffer[Int]):Int={
    val graph=getDirectedGraph(edges,n)
    val cou=Cou()
    postOrder(graph,cats,0,-1,cats(0),m,cou)
    println(cou.c)
    return cou.c
  }

  def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,pr:Int,curM:Int,m:Int,cou: Cou):Unit={
    if(curM<=m){

      var x=1
        for(i<- 0 until graph(n).length ){
          if(graph(n)(i)!=pr) {
            x=0
            if (cats(graph(n)(i)) == 0) {
              postOrder(graph, cats, graph(n)(i), n, 0, m, cou)
            } else {
              postOrder(graph, cats, graph(n)(i), n, curM + 1, m, cou)
            }
          }
        }
        cou.c+=x
      }
  }

  def getDirectedGraph(edges: ArrayBuffer[Int], N: Int): Array[ArrayBuffer[Int]] = {
    //Adjacency list representation is used to represent the graph

    //We have N vertices
    val graph = new Array[ArrayBuffer[Int]](N)

    //Every vertices can be associated to multiple adjacent vertices
    for (i <- 0 until N) {
      graph(i)= new ArrayBuffer[Int]()
    }

    //Every pair array elements represent a edge
    for (i <- 0 until edges.length by 2) {
      addDirectedEdge(graph, edges(i), edges(i + 1))
    }

    return graph
  }

  def addDirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {
    //It is a directed graph, so the an edge a to b can be used to travel from a to b
    graph(u) += v
    graph(v) += u
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/580/C
object KefaAndPark {
  case class Cou(var c:Int=0)
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var line=in.readLine()
    val n=line.split(" ")(0).toInt
    val m=line.split(" ")(1).toInt
    val cats=in.readLine().split(" ").map(_.toInt)
    val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for(i<- 0 until n-1){
      line=in.readLine()
      val u=line.split(" ")(0).toInt-1
      val v=(line.split(" ")(1).toInt-1)
      addUndirectedEdge(graph,u,v)
    }
    getNumberOfPossibleRestaurants(graph,n,m,cats)
  }

  def getNumberOfPossibleRestaurants(graph:Array[ArrayBuffer[Int]],n:Int,m:Int,cats:Array[Int]):Int={
    val cou=Cou()
    postOrder(graph,cats,0,-1,cats(0),m,cou)
    println(cou.c)
    return cou.c
  }

  def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,pr:Int,curM:Int,m:Int,cou: Cou):Unit={
    if(curM<=m){
      var x=1
      for(i<- 0 until graph(n).length ){
        if(graph(n)(i)!=pr) {
          x=0
          postOrder(graph, cats, graph(n)(i), n, cats(graph(n)(i))*curM+cats(graph(n)(i)), m, cou)
        }
      }
      cou.c+=x
    }
  }
  def addUndirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {
    //It is an undirected graph, so the an edge a to b can be used to travel both a to b and b to aa
    graph(u) += v
    graph(v) += u
  }
}

//package round321.c

import java.util.Scanner

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

  val n = sc.nextInt
  val m = sc.nextInt

  val hasCat = (0 until n).map(_ => sc.nextInt == 1)

  var tree = Array.fill[List[Int]](n)(Nil)

  (0 until (n-1)).foreach { _ =>
    val (a, b) = (sc.nextInt - 1, sc.nextInt - 1)
    tree(a) = b :: tree(a)
    tree(b) = a :: tree(b)
  }

  def dfs(v: Int, parent: Int, consCatsSoFar: Int): Int = {
    val consCats = if(hasCat(v)) 1 + consCatsSoFar else 0
    if(consCats > m) 0
    else {
      val children = tree(v).filterNot(_ == parent)
      if(children.isEmpty) 1
      else {
        children.foldLeft(0){ case (s, vNext) =>
          s + dfs(vNext, v, consCats)
        }
      }
    }
  }

  println(dfs(0, -1, 0))
}

object C580 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val isCat = readInts(n)
    val vis = Array.fill(n)(false)
    val _G = Array.fill(n)(collection.mutable.ArrayBuffer.empty[Int])
    for(i <- 0 until n-1){
      val in = readInts(2)
      _G(in(0)-1) += in(1)-1
      _G(in(1)-1) += in(0)-1
    }
    val G = _G.map(_.toArray)

    def dfs(idx: Int, cats: Int): Int = {
      val newCats = if(isCat(idx)==1) cats+1 else 0
      vis(idx) = true
      if(newCats <= m) {
        if(G(idx).length == 1 && idx!=0) {
          1
        } else {
          var sum = 0
          for (i <- G(idx)) {
            if(!vis(i))
              sum += dfs(i, newCats)
          }
          sum
        }
      } else {
        0
      }
    }

    var res = dfs(0, 0)
    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 annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _580C extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  val hasCats = IndexedSeq.fill(n)(nextInt == 1)
  val tree = map[Int].to(Set.empty[Int])
  repeat(n-1) {
    val (i, j) = (nextInt, nextInt)
    tree(i) = tree(i) + j
  }

  def solve(pos: Int, prevCats: Int): Int = {
    val cats = if (hasCats(pos - 1)) 1 + prevCats else 0
    //debug(pos, prevCats, cats, tree(pos))
    tree(pos).toSeq match {
      case _ if cats > m => 0
      case Nil => 1
      case children => children.map(solve(_, cats)).sum
    }
  }

  solve(1, 0)
}) {
  override def format(result: Result) = super.format(result)
}
/****************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  final def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

/**
 * @author netman
 */

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

object HelloWorld {

  class InputReader(reader: BufferedReader) {

    var tokenizer: StringTokenizer = null;

    def this(stream: InputStream) = {
      this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));
    }

    def this(f: File) = {
      this(new BufferedReader(new FileReader(f), (1 << 20)));
    }

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

    def nextInt(): Int = next().toInt

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

    def close() = reader.close();
  }

  class OutputWriter(writer: PrintWriter) {
    def this(stream: OutputStream) {
      this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));
    }

    def this(f: File) = {
      this(new PrintWriter(new BufferedWriter(new FileWriter(f))));
    }

    def print(x: Any) = writer.print(x);

    def println(x: Any) = writer.println(x);

    def close() = writer.close();
  }

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

  var a: Array[Int] = null
  var g: Array[ArrayBuffer[Int]] = null
  var m = 0
  var result = 0

  def dfs(v: Int, p: Int, cur: Int): Unit = {
    val ncur = if (a(v) == 0) 0 else cur + 1
    if (ncur > m) return
    if (g(v).length == 1) result += 1
    for (to <- g(v)) {
      if (to != p) {
        dfs(to, v, ncur)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val n = in.nextInt
    m = in.nextInt

    a = new Array[Int](n + 1)
    g = Array.fill[ArrayBuffer[Int]](n + 1)(new ArrayBuffer[Int])

    for (i <- 1 to n) {
      a(i) = in.nextInt
    }

    for (i <- 1 to n - 1) {
      val (x, y) = (in.nextInt, in.nextInt)
      g(x) += y
      g(y) += x
    }

    dfs(1, -1, 0)

    out.println(result)

    out.close
  }
}

/**
 * @author netman
 */

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

object HelloWorld {

  class InputReader(reader: BufferedReader) {

    var tokenizer: StringTokenizer = null;

    def this(stream: InputStream) = {
      this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));
    }

    def this(f: File) = {
      this(new BufferedReader(new FileReader(f), (1 << 20)));
    }

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

    def nextInt(): Int = next().toInt

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

    def close() = reader.close();
  }

  class OutputWriter(writer: PrintWriter) {
    def this(stream: OutputStream) {
      this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));
    }

    def this(f: File) = {
      this(new PrintWriter(new BufferedWriter(new FileWriter(f))));
    }

    def print(x: Any) = writer.print(x);

    def println(x: Any) = writer.println(x);

    def close() = writer.close();
  }

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

  var a: Array[Int] = null
  var g: Array[ArrayBuffer[Int]] = null
  var m = 0
  var result = 0

  def dfs(v: Int, p: Int, cur: Int): Unit = {
    val ncur = if (a(v) == 0) 0 else cur + 1
    if (ncur <= m) {
    if (g(v).length == 1) result += 1
    for (to <- g(v)) {
      if (to != p) {
        dfs(to, v, ncur)
      }
    }
    }
  }

  def main(args: Array[String]): Unit = {
    val n = in.nextInt
    m = in.nextInt

    a = new Array[Int](n + 1)
    g = Array.fill[ArrayBuffer[Int]](n + 1)(new ArrayBuffer[Int])

    for (i <- 1 to n) {
      a(i) = in.nextInt
    }

    for (i <- 1 to n - 1) {
      val (x, y) = (in.nextInt, in.nextInt)
      g(x) += y
      g(y) += x
    }

    dfs(1, -1, 0)

    out.println(result)

    out.close
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/580/C
object KefaAndPark {
  case class Cou(var c:Int=0)
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var line=in.readLine()
    val n=line.split(" ")(0).toInt
    val m=line.split(" ")(1).toInt
    val cats=in.readLine().split(" ").map(_.toInt)
    val edges=new ArrayBuffer[Int]()
    for(i<- 0 until n-1){
      line=in.readLine()
      edges+=(line.split(" ")(0).toInt-1)
      edges+=(line.split(" ")(1).toInt-1)
    }
    getNumberOfPossibleRestaurants(n,m,cats,edges)
  }

  def getNumberOfPossibleRestaurants(n:Int,m:Int,cats:Array[Int],edges:ArrayBuffer[Int]):Int={
    val graph=getDirectedGraph(edges,n)
    val cou=Cou()
    postOrder(graph,cats,0,-1,cats(0),m,cou)
    println(cou.c)
    return cou.c
  }

  def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,pr:Int,curM:Int,m:Int,cou: Cou):Unit={
    if(curM<=m){
      if(graph(n).length==1){
        cou.c+=1
      }else{
        for(i<- 0 until graph(n).length if(graph(n)(i)!=pr)){
          if(cats(graph(n)(i))==0) {
            postOrder(graph, cats, graph(n)(i),n, 0, m, cou)
          }else{
            postOrder(graph, cats, graph(n)(i),n, curM+1, m, cou)
          }
        }
      }
    }
  }

  def getDirectedGraph(edges: ArrayBuffer[Int], N: Int): Array[ArrayBuffer[Int]] = {
    //Adjacency list representation is used to represent the graph

    //We have N vertices
    val graph = new Array[ArrayBuffer[Int]](N)

    //Every vertices can be associated to multiple adjacent vertices
    for (i <- 0 until N) {
      graph(i)= new ArrayBuffer[Int]()
    }

    //Every pair array elements represent a edge
    for (i <- 0 until edges.length by 2) {
      addDirectedEdge(graph, edges(i), edges(i + 1))
    }

    return graph
  }

  def addDirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {
    //It is a directed graph, so the an edge a to b can be used to travel from a to b
    graph(u) += v
    graph(v) += u
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/580/C
object KefaAndPark {
  case class Cou(var c:Int=0)
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var line=in.readLine()
    val n=line.split(" ")(0).toInt
    val m=line.split(" ")(1).toInt
    val cats=in.readLine().split(" ").map(_.toInt)
    val edges=new ArrayBuffer[Int]()
    for(i<- 0 until n-1){
      line=in.readLine()
      edges+=line.split(" ")(0).toInt-1
      edges+=line.split(" ")(1).toInt-1
    }
    getNumberOfPossibleRestaurants(n,m,cats,edges)
  }

  def getNumberOfPossibleRestaurants(n:Int,m:Int,cats:Array[Int],edges:ArrayBuffer[Int]):Int={
    val graph=getDirectedGraph(edges,n)
    val cou=Cou()
    if(cats(0)==0)
      postOrder(graph,cats,0,0,m,cou)
    else
      postOrder(graph,cats,0,1,m,cou)
    println(cou.c)
    return cou.c
  }

  def postOrder(graph:Array[ArrayBuffer[Int]],cats:Array[Int],n:Int,curM:Int,m:Int,cou: Cou):Unit={
    if(curM<=m){
      if(graph(n).length==0){
        cou.c+=1
      }else{
        for(i<- 0 until graph(n).length){
          if(cats(graph(n)(i))==0) {
            postOrder(graph, cats, graph(n)(i), 0, m, cou)
          }else{
            postOrder(graph, cats, graph(n)(i), curM+1, m, cou)
          }
        }
      }
    }
  }

  def getDirectedGraph(edges: ArrayBuffer[Int], N: Int): Array[ArrayBuffer[Int]] = {
    //Adjacency list representation is used to represent the graph

    //We have N vertices
    val graph = new Array[ArrayBuffer[Int]](N)

    //Every vertices can be associated to multiple adjacent vertices
    for (i <- 0 until N) {
      graph(i)= new ArrayBuffer[Int]()
    }

    //Every pair array elements represent a edge
    for (i <- 0 until edges.length by 2) {
      addDirectedEdge(graph, edges(i), edges(i + 1))
    }

    return graph
  }

  def addDirectedEdge(graph: Array[ArrayBuffer[Int]], u: Int, v: Int): Unit = {
    //It is a directed graph, so the an edge a to b can be used to travel from a to b
    graph(u) += v
  }
}

object C580 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val isCat = readInts(n)
    val vis = Array.fill(n)(false)
    val _G = Array.fill(n)(collection.mutable.ArrayBuffer.empty[Int])
    for(i <- 0 until n-1){
      val in = readInts(2).sorted
      _G(in(0)-1) += in(1)-1
    }
    val G = _G.map(_.toArray)
    //bfs
    val q = collection.mutable.Queue.empty[(Int, Int)]
    q.enqueue((0, 0))
    while(q.nonEmpty) {
      val (top, cats) = q.dequeue()
      if(isCat(top) == 1) {
        if(cats+1 <= m) {
          vis(top) = true
          for(i <- G(top)) {
            q.enqueue((i, cats+1))
          }
        }
      } else {
        vis(top) = true
        for(i <- G(top)) {
          q.enqueue((i, 0))
        }
      }
    }
    var res = 0
    for(i <- 0 until n) {
      if(G(i).isEmpty && vis(i)) {
        res += 1
      }
    }
    println(res)
  }

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

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

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

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

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

}

object C580 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val isCat = readInts(n)
    val vis = Array.fill(n)(false)
    val _G = Array.fill(n)(collection.mutable.ArrayBuffer.empty[Int])
    for(i <- 0 until n-1){
      val in = readInts(2)
      _G(in(0)-1) += in(1)-1
    }
    val G = _G.map(_.toArray)
    //bfs
    val q = collection.mutable.Queue.empty[(Int, Int)]
    q.enqueue((0, 0))
    while(q.nonEmpty) {
      val (top, cats) = q.dequeue()
      if(isCat(top) == 1) {
        if(cats+1 <= m) {
          vis(top) = true
          for(i <- G(top)) {
            q.enqueue((i, cats+1))
          }
        }
      } else {
        vis(top) = true
        for(i <- G(top)) {
          q.enqueue((i, 0))
        }
      }
    }
    var res = 0
    for(i <- 0 until n) {
      if(G(i).isEmpty && vis(i)) {
        res += 1
      }
    }
    println(res)
  }

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

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

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

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

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

}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _580C extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  val hasCats = IndexedSeq.fill(n)(nextInt == 1)
  val tree = map[Int].to(Set.empty[Int])
  repeat(n-1) {
    val (i, j) = (nextInt, nextInt)
    val (u, v) = (i min j, i max j)
    tree(u) = tree(u) + v
  }

  def solve(pos: Int, prevCats: Int): Int = {
    val cats = if (hasCats(pos - 1)) 1 + prevCats else 0
    tree(pos).toSeq match {
      case _ if cats > m => 0
      case Nil => 1
      case children => children.map(solve(_, cats)).sum
    }
  }

  solve(1, 0)
}) {
  override def format(result: Result) = super.format(result)
}
/****************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  final def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _580C extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  val hasCats = IndexedSeq.fill(n)(nextInt == 1)
  val tree = mutable.Map.empty[Int, Set[Int]] withDefaultValue Set.empty[Int]
  repeat(n-1) {
    val (i, j) = (nextInt, nextInt)
    tree(i) = tree(i) + j
  }

  def solve(pos: Int, prevCats: Int): Int = {
    val cats = if (hasCats(pos - 1)) 1 + prevCats else 0
    if (cats > m) { // this path has > m consecutive cats, no point continuing
      0
    } else {
      val children = tree(pos)
      if (children.isEmpty) { // a leaf node
        1
      } else { // an inner node
        children.toSeq.map(solve(_, cats)).sum
      }
    }
  }

  solve(1, 0)
}) {
  override def format(result: Result) = super.format(result)
}
/****************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
}


Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:  Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).  The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.

The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).

Print m integers — the responses to Eugene's queries in the order they occur in the input.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val countPlus = data.count(_ == 1)
  val countMinus = n - countPlus
  val res = (1 to m).map{ _ =>
    val Array(l, r) = in.next().split(" ").map(_.toInt)
    val distance = r - l + 1
    if (distance % 2 == 1 || (distance / 2 > countPlus || distance / 2 > countMinus))
      0
    else
      1
  }
  println(res.mkString("\n"))
}

object Main {
  def main(args: Array[String]) = {
    val m = readLine.dropWhile(_ != ' ').tail.toInt
    var a = 0
    var b = 0

    for(x <- readLine.split(" "))
      x.toInt match {
        case 1  => a += 1
        case -1 => b += 1
        case _  =>
      }

    for(i <- 1 to m) {
      val line = readLine
      val l = line.takeWhile(_ != ' ').toInt
      val r = line.dropWhile(_ != ' ').tail.toInt
      val x = r - l + 1

      if(x % 2 == 0 && x / 2 <= Math.min(a, b))
        println(1)
      else
        println(0)
    }
  }
}

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

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

  val N, M = sc.nextInt
  val as = Array.fill(N)(sc.nextInt)
  val max = 2 * (as.count(_ == 1) min as.count(_ == -1))

  def isEven(n: Int): Boolean = n % 2 == 0

  for (i <- 0 until M) {
    val l, r = sc.nextInt
    val y = r - l + 1
    val res = if (y > 0 && y <= max && isEven(y)) 1 else 0
    out.println(res)
  }

  out.close
}

object Main {
  def main(args: Array[String]): Unit = {
    val nk = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val neg = a.count(_ == -1)
    val pos = a.count(_ == 1)
    val min = neg.min(pos)

    for (_ <- 1 to nk(1)) {
      val ix = readLine().split(" ").map(_.toInt)
      val i0 = ix(0)
      val i1 = ix(1)
      if ((i1 - i0 + 1) % 2 == 1) println("0")
      else if ((i1 - i0 + 1) / 2 <= min) println("1")
      else println("0")
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val countPlus = data.count(_ == 1)
  val countMinus = n - countPlus
  val res = (1 to m).map{ _ =>
    val Array(l, r) = in.next().split(" ").map(_.toInt)
    val distance = r - l + 1
    if (distance % 2 == 1 || (distance / 2 < countPlus || distance / 2 < countMinus))
      0
    else
      1
  }
  println(res.mkString("\n"))
}

object Main {
  def main(args: Array[String]): Unit = {
    val nk = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val neg = a.count(_ == -1)
    val pos = a.count(_ == 1)
    val min = neg.min(pos)

    for (_ <- 1 to nk(1)) {
      val ix = readLine().split(" ").map(_.toInt)
      val i0 = ix(0)
      val i1 = ix(1)
      if ((i1 - i0 + 1) % 2 == 1) println("0")
      else if ((i1 - i1 + 1) / 2 <= min) println("1")
      else println("0")
    }
  }
}


Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:   A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars.  Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.

The first input line contains number n (1 ≤ n ≤ 5000) — amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 ≤ x ≤ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 ≤ x ≤ 2000).

Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.

7
win 10
win 5
win 3
sell 5
sell 3
win 10
sell 10

import java.math.BigInteger
import java.util
import java.util._
import java.io._

object D {

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

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

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

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

  def noUsedFromTo(from: Int, to: Int, used: Array[Boolean]): Boolean = {
    var flag = true
    for (i <- from to to) {
      flag &= !used(i)
    }
    return flag
  }

  def solve: Int = {
    val n = nextInt
    val events = new Array[(Boolean, Int, Int)](n)
    val needToSell = new util.TreeSet[Int]()
    val used = new Array[Boolean](n)
    for (i <- 0 until n) {
      if (next == "win") {
        events(i) = (true, nextInt, i)
      } else {
        events(i) = (false, nextInt, i)
        needToSell.add(events(i)._2)
      }
    }
    var ans: BigInteger = BigInteger.ZERO
    val it = needToSell.descendingIterator
    while (it.hasNext) {
      val price = it.next
      val pos = events.find(x => !x._1 && x._2 == price).get._3
      var i = pos - 1
      while (i >= 0) {
        if (events(i)._1 && events(i)._2 == price && noUsedFromTo(i, pos, used)) {
          ans = ans.add(BigInteger.valueOf(2).pow(price))
          for (j <- i to pos) {
            used(j) = true
          }
          i = -1
        }
        i -= 1
      }
    }
    out.println(ans)
    return 1
  }

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

import java.math.BigInteger
import java.util
import java.util._
import java.io._

object D {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val events = new Array[(Boolean, Int, Int)](n)
    val needToSell = new util.TreeSet[Int]()
    val used = new Array[Boolean](n)
    for (i <- 0 until n) {
      if (next == "win") {
        events(i) = (true, nextInt, i)
      } else {
        events(i) = (false, nextInt, i)
        needToSell.add(events(i)._2)
      }
    }
    var ans: BigInteger = BigInteger.ZERO
    val it = needToSell.descendingIterator
    while (it.hasNext) {
      val price = it.next
      val pos = events.find(x => !x._1 && x._2 == price).get._3
      var i = pos - 1
      while (i >= 0) {
        if (events(i)._1 && events(i)._2 == price && !used(i)) {
          ans = ans.add(BigInteger.valueOf(2).pow(price))
          for (j <- i to pos) {
            used(j) = true
          }
          i = -1
        }
        i -= 1
      }
    }
    out.println(ans)
    return 1
  }

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