### subroutines

def parse_tree(ts)
  if ts[$pos] =~ /[0-9]/
    c = ts[$pos]
    $pos += 1
    return $rs[c.to_i - 1]
  end

  tr = [$nct]
  $nct += 1

  $pos += 1
  tr << parse_tree(ts)
  $pos += 1
  tr << parse_tree(ts)
  $pos += 1

  tr
end

def calc_tree(tr, ops)
  return tr if tr.class != Array

  sl = calc_tree(tr[1], ops)
  sr = calc_tree(tr[2], ops)

  case ops[tr[0]]
  when 0
    sl &= sr
  when 1
    sl |= sr
  when 2
    sl ^= sr
  end

  sl
end

### main

max_bits = 15

loop do
  treestr = gets.strip
  break if treestr == 'END'

  $n = gets.to_i
  $rs = []

  $n.times do
    $rs << gets.split.join.to_i(2)
  end

  $pos = 0
  $nct = 0

  tr = parse_tree(treestr)
  #p tr

  ops = $nct.times.map{0}
  count = 0

  loop do
    sbits = calc_tree(tr, ops)
    count += 1 if sbits == max_bits

    i = 0
    while i < $nct
      ops[i] += 1
      break if ops[i] <= 2
      ops[i] = 0
      i += 1
    end

    break if i >= $nct
  end

  puts count
end