class Tree
  AND, OR, XOR = (0..2).to_a
  ALL = "1111".to_i(2)

  def initialize(exp, sweet)
    @size = 0
    @root = parse(exp, sweet)
  end

  class Node
    attr_accessor :left, :right, :value
  end

  def parse(exp, sweet)
    node = Node.new
    case exp.chr
      when "("
        @size += 1
        exp.slice!(0) # "("
        node.left = parse(exp, sweet)
        exp.slice!(0) # " "
        node.right = parse(exp, sweet)
        exp.slice!(0) # ")"
      else
        node.value = sweet[exp.slice!(0).to_i - 1]
    end
    node
  end

  def solve(depth = 0, operator = Array.new)
    return (calculate(operator.dup) == ALL ? 1 : 0) if (depth == @size)
    [AND, OR, XOR].inject(0){|sum, op|
      operator[depth] = op
      sum + solve(depth + 1, operator)
    }
  end

  def calculate(operator, node = @root)
    return node.value if node.value
    case operator.shift
      when AND
        calculate(operator, node.left) & calculate(operator, node.right)
      when OR
        calculate(operator, node.left) | calculate(operator, node.right)
      when XOR
        calculate(operator, node.left) ^ calculate(operator, node.right)
    end
  end
end

until (exp = gets.chomp) == "END"
  p Tree.new(exp, gets.to_i.times.map{gets.delete(" ").to_i(2)}).solve
end