import scala.annotation.tailrec
object Main extends App {

  import scala.io.StdIn._

  solve
  def solve: Unit = {
    val exp = readLine.trim
    if (exp == "END") return
    val leaf = Array.tabulate(readInt){_ ⇒
      val Array(a, b, c, d) = readLine.trim.split(' ').map(_.toInt == 1)
      Leaf(CandySet(a, b, c, d))
    }
    Tree.parse(exp, leaf) match {
      case Some(r) ⇒ println(r.calPattern(CandySet(true, true, true, true)))
      case _ ⇒ ???
    }
    solve

  }
  object Tree {
    def parse(express: String, leaf: Array[Leaf]): Option[Node] = {
      implicit val l = leaf
      express.toList match {
        case n Tree Nil ⇒ Some(n)
        case _ ⇒ None
      }
    }
    def unapply(arg:List[Char])(implicit leaf: Array[Leaf]): Option[(Node, List[Char])] = {
      arg match {
        case n::t if n.isDigit ⇒ Some(leaf(n.asDigit - 1), t)
        case '('::(l Tree ' '::(r Tree ')'::t)) ⇒Some(new InterNode(l, r), t)
        case _ ⇒ None
      }
    }
  }
  sealed trait Node {
    def calPattern(candySet: CandySet): Long
  }
  class InterNode(val left: Node, right: Node) extends Node {
    override def calPattern(candySet: CandySet): Long = memo(candySet.toIndex) match {
      case Some(r) ⇒ r
      case None ⇒
        val and = CandySet.all.map{l ⇒
          CandySet.all.filter(r ⇒ l.and(r) == candySet).map(r ⇒ right.calPattern(r)).sum * left.calPattern(l)
        }.sum
        val or = CandySet.all.map{l ⇒
          CandySet.all.filter(r ⇒ l.or(r) == candySet).map(r ⇒ right.calPattern(r)).sum * left.calPattern(l)
        }.sum
        val xor = CandySet.all.map{l ⇒
          CandySet.all.filter(r ⇒ l.xor(r) == candySet).map(r ⇒ right.calPattern(r)).sum * left.calPattern(l)
        }.sum
        memo(candySet.toIndex) = Some(and + or + xor)
        and + or + xor
    }
    private val memo = Array.tabulate(16){_ ⇒ None: Option[Long]}
  }

  case class Leaf(state: CandySet) extends Node {
    override def calPattern(candySet: CandySet): Long = if (candySet == state) 1 else 0
  }
  object CandySet{
    val all: List[CandySet] = (0 until 4).map{_ ⇒ List(true, false)}.foldLeft(Nil::Nil:List[List[Boolean]]){case (a, b) ⇒ a.flatMap{l ⇒ b.map{r ⇒ r::l}}}.map{case a::b::c::d::Nil ⇒ CandySet(a, b, c, d); case _ ⇒ ???}
  }
  case class CandySet(a: Boolean, b: Boolean, c: Boolean, d: Boolean) {
    def toIndex: Int = List(a, b, c, d).map {if (_) 1 else 0}.foldLeft(0) { case (l, r) ⇒ l * 2 + r }
    def and(that: CandySet): CandySet = map(that)(_.&&)
    def or(that: CandySet): CandySet = map(that)(_.||)
    def xor(that: CandySet): CandySet = map(that)(_.^)
    @inline
    private def map(that: CandySet)(@inline func: Boolean ⇒ Boolean ⇒ Boolean): CandySet = CandySet(func(a)(that.a), func(b)(that.b), func(c)(that.c), func(d)(that.d))
  }
  implicit class Extension[T](val value :T) extends AnyVal {
    @inline
    def let[A](@inline func: T ⇒ A): A = func(value)
    @inline
    def also(@inline func: T ⇒ Unit): T = {func(value); value}
  }
}

